using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

public partial class GonzalesMyDraftDetail : System.Web.UI.Page
{
    #region Variables

    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;
    protected GonzalesClaimHeader ResultObj = null;
    protected readonly int TotalColumns = 20;
    protected readonly int EveryExtraRow = 10;
    protected short Counter = 0;
    protected int CurRow = 1;
    protected int NewRow = 1;

    #region ClaimHavingCreditCard
    protected bool ClaimHavingCreditCard
    {
        get
        {
            return (bool)ViewState["ClaimHavingCreditCard"];
        }

        set
        {
            ViewState["ClaimHavingCreditCard"] = value;
        }
    }
    #endregion

    #region ClaimInternalID
    protected string ClaimInternalID
    {
        get
        {
            return ViewState["ClaimInternalID"].ToString();
        }

        set
        {
            ViewState["ClaimInternalID"] = value;
        }
    }
    #endregion    

    #region TypeOfCreditCardPayment
    protected TypeOfCreditCardPayment CreditCardPaymentType
    {
        get
        {
            return CreditCardManager.GetCreditCardPaymentTypeFromCode(Convert.ToInt32(ViewState["TypeOfCreditCardPayment"]));
        }

        set
        {
            ViewState["TypeOfCreditCardPayment"] = CreditCardManager.GetCreditCardPaymentTypeInCode((TypeOfCreditCardPayment)value);
        }
    }
    #endregion

    #region Components for Claim Detail Table Grid

    protected bool IsComponentSetup = false;
    protected MasterBaseCollection ClaimTypes = null;
    protected MasterBaseCollection Countries = null;
    protected MasterBaseCollection Currencies = null;
    protected int ClaimDetailRowBuiltCounter = 0;   // everytime will be 0

    protected DropDownList MasterDropDownCurrencies = new DropDownList();

    #region ActualNumberOfRow
    protected int ActualNumberOfRow
    {
        get
        {
            return (int)ViewState["ActualNumberOfRow"];
        }

        set
        {
            ViewState["ActualNumberOfRow"] = value;
        }
    }
    #endregion

    #region ClaimDetailIDList
    protected ArrayList ClaimDetailIDList
    {
        get
        {
            return (ArrayList)ViewState["ClaimDetailIDList"];
        }

        set
        {
            ViewState["ClaimDetailIDList"] = value;
        }
    }
    #endregion

    #endregion

    #region Common Variables for Language Translation

    #region ValidationText
    protected string ValidationText
    {
        get
        {
            return ViewState["ValidationText"].ToString();
        }

        set
        {
            ViewState["ValidationText"] = value;
        }
    }
    #endregion

    #region HeaderDeleteRemarks
    protected string HeaderDeleteRemarks
    {
        get
        {
            return ViewState["HeaderDeleteRemarks"].ToString();
        }

        set
        {
            ViewState["HeaderDeleteRemarks"] = value;
        }
    }
    #endregion

    #region ExpandLineItemConfirmation
    protected string ExpandLineItemConfirmation
    {
        get
        {
            return ViewState["ExpandLineItemConfirmation"].ToString();
        }

        set
        {
            ViewState["ExpandLineItemConfirmation"] = value;
        }
    }
    #endregion

    #region ExpandLineItemToolTips
    protected string ExpandLineItemToolTips
    {
        get
        {
            return ViewState["HeaderExpandLineItemToolTips"].ToString();
        }

        set
        {
            ViewState["HeaderExpandLineItemToolTips"] = value;
        }
    }
    #endregion

    #region ExchangeRateAlert
    protected string ExchangeRateAlert
    {
        get
        {
            return ViewState["PromptExchangeRateAlert"].ToString();
        }

        set
        {
            ViewState["PromptExchangeRateAlert"] = value;
        }
    }
    #endregion

    #region LimitExceed
    protected string LimitExceed
    {
        get
        {
            return ViewState["LimitExceed"].ToString();
        }

        set
        {
            ViewState["LimitExceed"] = value;
        }
    }
    #endregion

    #region LimitPerHead
    protected string LimitPerHead
    {
        get
        {
            return ViewState["LimitPerHead"].ToString();
        }

        set
        {
            ViewState["LimitPerHead"] = value;
        }
    }
    #endregion

    #region LimitAmountTodate
    protected string LimitAmountTodate
    {
        get
        {
            return ViewState["LimitAmountTodate"].ToString();
        }

        set
        {
            ViewState["LimitAmountTodate"] = value;
        }
    }
    #endregion

    #region LimitAmount
    protected string LimitAmount
    {
        get
        {
            return ViewState["LimitAmount"].ToString();
        }

        set
        {
            ViewState["LimitAmount"] = value;
        }
    }
    #endregion

    #region LimitStrict
    protected string LimitStrict
    {
        get
        {
            return ViewState["LimitStrict"].ToString();
        }

        set
        {
            ViewState["LimitStrict"] = value;
        }
    }
    #endregion

    #region LimitYes
    protected string LimitYes
    {
        get
        {
            return ViewState["LimitYes"].ToString();
        }

        set
        {
            ViewState["LimitYes"] = value;
        }
    }
    #endregion

    #region LimitNo
    protected string LimitNo
    {
        get
        {
            return ViewState["LimitNo"].ToString();
        }

        set
        {
            ViewState["LimitNo"] = value;
        }
    }
    #endregion

    #region SaveDataError
    protected string SaveDataError
    {
        get
        {
            return ViewState["SaveDataError"].ToString();
        }

        set
        {
            ViewState["SaveDataError"] = value;
        }
    }
    #endregion

    #region SortingError
    protected string SortingError
    {
        get
        {
            return ViewState["SortingError"].ToString();
        }

        set
        {
            ViewState["SortingError"] = value;
        }
    }
    #endregion

    #region ErrorMessage
    protected string ErrorMessage
    {
        get
        {
            return ViewState["ErrorMessage"].ToString();
        }

        set
        {
            ViewState["ErrorMessage"] = value;
        }
    }
    #endregion

    #region NoReceipt
    protected string NoReceipt
    {
        get
        {
            return ViewState["NoReceipt"].ToString();
        }

        set
        {
            ViewState["NoReceipt"] = value;
        }
    }
    #endregion

    #region PersonalExpense
    protected string PersonalExpense
    {
        get
        {
            return ViewState["PersonalExpense"].ToString();
        }

        set
        {
            ViewState["PersonalExpense"] = value;
        }
    }
    #endregion

    #region ExpiryMessage2
    protected string ExpiryMessage2
    {
        get
        {
            return ViewState["ExpiryMessage2"].ToString();
        }

        set
        {
            ViewState["ExpiryMessage2"] = value;
        }
    }
    #endregion

    #region ExpiryMessage1
    protected string ExpiryMessage1
    {
        get
        {
            return ViewState["ExpiryMessage1"].ToString();
        }

        set
        {
            ViewState["ExpiryMessage1"] = value;
        }
    }
    #endregion

    #region InvalidDateFormat
    protected string InvalidDateFormat
    {
        get
        {
            return ViewState["InvalidDateFormat"].ToString();
        }

        set
        {
            ViewState["InvalidDateFormat"] = value;
        }
    }
    #endregion

    #region ItemExpenseDetail
    protected string ItemExpenseDetail
    {
        get
        {
            return ViewState["ItemExpenseDetail"].ToString();
        }

        set
        {
            ViewState["ItemExpenseDetail"] = value;
        }
    }
    #endregion

    #region ItemClaimedDate
    protected string ItemClaimedDate
    {
        get
        {
            return ViewState["ItemClaimedDate"].ToString();
        }

        set
        {
            ViewState["ItemClaimedDate"] = value;
        }
    }
    #endregion

    #region ItemLocation
    protected string ItemLocation
    {
        get
        {
            return ViewState["ItemLocation"].ToString();
        }

        set
        {
            ViewState["ItemLocation"] = value;
        }
    }
    #endregion

    #region ItemReceiptNo
    protected string ItemReceiptNo
    {
        get
        {
            return ViewState["ItemReceiptNo"].ToString();
        }

        set
        {
            ViewState["ItemReceiptNo"] = value;
        }
    }
    #endregion

    #region ItemCreditCardDetail
    protected string ItemCreditCardDetail
    {
        get
        {
            return ViewState["ItemCreditCardDetail"].ToString();
        }

        set
        {
            ViewState["ItemCreditCardDetail"] = value;
        }
    }
    #endregion

    #region ItemClaimantRemarks
    protected string ItemClaimantRemarks
    {
        get
        {
            return ViewState["ItemClaimantRemarks"].ToString();
        }

        set
        {
            ViewState["ItemClaimantRemarks"] = value;
        }
    }
    #endregion

    #region ItemClaimedAmount
    protected string ItemClaimedAmount
    {
        get
        {
            return ViewState["ItemClaimedAmount"].ToString();
        }

        set
        {
            ViewState["ItemClaimedAmount"] = value;
        }
    }
    #endregion

    #region ItemTax
    protected string ItemTax
    {
        get
        {
            return ViewState["ItemTax"].ToString();
        }

        set
        {
            ViewState["ItemTax"] = value;
        }
    }
    #endregion

    #region ItemCurrency
    protected string ItemCurrency
    {
        get
        {
            return ViewState["ItemCurrency"].ToString();
        }

        set
        {
            ViewState["ItemCurrency"] = value;
        }
    }
    #endregion

    #region ItemExRate
    protected string ItemExRate
    {
        get
        {
            return ViewState["ItemExRate"].ToString();
        }

        set
        {
            ViewState["ItemExRate"] = value;
        }
    }
    #endregion

    #region ItemLocalAmount
    protected string ItemLocalAmount
    {
        get
        {
            return ViewState["ItemLocalAmount"].ToString();
        }

        set
        {
            ViewState["ItemLocalAmount"] = value;
        }
    }
    #endregion

    #region ItemProjectID
    protected string ItemProjectID
    {
        get
        {
            return ViewState["ItemProjectID"].ToString();
        }

        set
        {
            ViewState["ItemProjectID"] = value;
        }
    }
    #endregion

    #endregion

    #region Category

    protected CategoryOfClaim Category
    {
        get
        {
            return (CategoryOfClaim)ViewState["Category"];
        }

        set
        {
            ViewState["Category"] = value;
        }
    }

    #endregion

    #region DefaultCurrencyCode

    protected string DefaultCurrencyCode
    {
        get
        {
            return ViewState["DefaultCurrencyCode"].ToString();
        }

        set
        {
            ViewState["DefaultCurrencyCode"] = value;
        }
    }

    #endregion

    #region DefaultCountryCode

    protected string DefaultCountryCode
    {
        get
        {
            return ViewState["DefaultCountryCode"].ToString();
        }

        set
        {
            ViewState["DefaultCountryCode"] = value;
        }
    }

    #endregion

    #region DefaultExchangeRate

    protected decimal DefaultExchangeRate
    {
        get
        {
            return decimal.Parse(ViewState["DefaultExchangeRate"].ToString());
        }

        set
        {
            ViewState["DefaultExchangeRate"] = value;
        }
    }

    #endregion

    #region PageStartTime
    protected DateTime PageStartTime
    {
        set
        {
            ViewState["PageStartTime"] = value;
        }

        get
        {
            return (DateTime)ViewState["PageStartTime"];
        }
    }
    #endregion

    #endregion

    #region Events

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();      
  
        // switch off error message box on every load
        this.Table_MessageBox.Visible = false;

        // siwthc off policy checking box on every load
        this.Table_PolicyChecking_Pass.Visible = this.Table_PolicyChecking_Fail.Visible = false;

        // This action is needed only at the first load
        if (!IsPostBack)
        {
            // Language
            this.SwitchLanguage();

            // load header
            this.LoadData();

            // Page Componenegt
            this.PageComponentSetup();

            // set the category
            this.Category = this.ResultObj.Category;

            // initial default as no credit card
            this.ClaimHavingCreditCard = false;
            this.PageStartTime = DateTime.Now;

            this.SetTimer();
        }

        // Table Bulding        
        if (!IsPostBack)
        {
            // build row
            this.ClaimDetailIDList = new ArrayList();            
            this.ActualNumberOfRow = 0;            
            int MinNumberOfRow = 5;
            this.ActualNumberOfRow = (ResultObj.ClaimDetails.Count > MinNumberOfRow) ? ResultObj.ClaimDetails.Count : MinNumberOfRow;
        }

        this.BuiltTable();
        this.TableGridComponengtSetup();

        if (!IsPostBack)
        {
            for (int x = 0; x < ActualNumberOfRow; x++)
            {
                if (x < ResultObj.ClaimDetails.Count)
                {
                    this.BuildRow(ResultObj.ClaimDetails[x].InternalID);
                }
                else
                {
                    this.BuildRow();
                }
            }
        }
        else
        {
            for (int x = 0; x < this.ActualNumberOfRow; x++)
            {
                if (x < this.ClaimDetailIDList.Count)
                {
                    this.BuildRow(this.ClaimDetailIDList[x].ToString());
                }
                else
                {
                    this.BuildRow();
                }
            }
        }

        // After built row, then load the rest of data into detail grid
        // This action is needed only at the first load
        if (!IsPostBack && this.ResultObj.ClaimDetails != null)
        {
            this.ResultObj.ClaimDetails.SortByOrder();
            this.LoadIntoDetailGrid();
            this.CalculateTotalForDisplay();            

            // Less Advance Box            
            this.TextBox_TotalAmountAlreadyPaid.Style.Add (HtmlTextWriterStyle.TextAlign, "right");
            this.TextBox_TotalPersonalExpenses.Style.Add(HtmlTextWriterStyle.TextAlign, "right");

            this.TextBox_TotalPersonalExpenses.Attributes["onfocus"] = this.TextBox_TotalPersonalExpenses.Attributes["onClick"] = "NoEdit(this);";

            if (this.ClaimHavingCreditCard)
            {
                if (this.CreditCardPaymentType == TypeOfCreditCardPayment.PaidByCompany)
                {
                    this.TextBox_TotalAmountAlreadyPaid.CssClass = "DetailGridTextBoxNoEdit";
                    this.TextBox_TotalAmountAlreadyPaid.TabIndex = -1;
                    this.TextBox_TotalAmountAlreadyPaid.Attributes["onfocus"] = this.TextBox_TotalAmountAlreadyPaid.Attributes["onClick"] = "NoEdit(this);";
                }
                else
                {
                    this.TextBox_TotalAmountAlreadyPaid.CssClass = "DetailGridTextBox";
                }
            }
            else
            {
                // non-credit card
                this.TextBox_TotalAmountAlreadyPaid.CssClass = "DetailGridTextBoxNoEdit";
                this.TextBox_TotalAmountAlreadyPaid.TabIndex = -1;
                this.TextBox_TotalAmountAlreadyPaid.Attributes["onfocus"] = this.TextBox_TotalAmountAlreadyPaid.Attributes["onClick"] = "NoEdit(this);";
            }
        }

        // Javascript
        this.GeneralVariable(); // General variable
        this.GenerateExchangeRate(); // Exchange Rate
        this.GenerateExpenseDetail();   // Expense Detail
        this.GenerateCountryCurrencyRefference(); // currency        
        this.GenerateClaimedAmountLimitation();
    }
    #endregion

    #region Button_AddMore_Click
    protected void Button_AddMore_Click(object sender, EventArgs e)
    {
        this.TableGridComponengtSetup();
        ActualNumberOfRow += this.EveryExtraRow;

        for (int x = 0; x < this.EveryExtraRow; x++)
        {
            this.BuildRow();
        }

        TimeSpan TimeDiff = new TimeSpan(DateTime.Now.Ticks - this.PageStartTime.Ticks);
        ViewState["mins"] = TimeDiff.Minutes;
        ViewState["secs"] = TimeDiff.Seconds;
        this.SetTimer();
    }
    #endregion

    #region Button_Remove_Click
    protected void Button_Remove_Click(object sender, EventArgs e)
    {
        //reset curRow
        CurRow = 1;
        
        int x = 1;
        ArrayList ItemsToDelete = new ArrayList();

        while (x < (this.Table_ClaimDetailGrid.Rows.Count))
        {
            if (((CheckBox)this.Table_ClaimDetailGrid.Rows[x].Cells[0].Controls[0]).Checked)
            {
                // keeping track of parent to delete
                ItemsToDelete.Add(this.Table_ClaimDetailGrid.Rows[x].ID);

                for (int y = 0; y < this.ClaimDetailIDList.Count; y++)
                {
                    if (this.ClaimDetailIDList[y].ToString().CompareTo(this.Table_ClaimDetailGrid.Rows[x].ID) == 0)
                    {
                        this.ClaimDetailIDList.RemoveAt(y);
                    }
                }
                
                this.Table_ClaimDetailGrid.Rows.RemoveAt(x);
                this.ActualNumberOfRow--;
            }
            else
            {
                x++;
            }
        }     
   
        // check for ophan item
        x = 1;
        bool Removed = false;
        while (x < this.Table_ClaimDetailGrid.Rows.Count)
        {
            Removed = false;

            for (int y = 0; y < ItemsToDelete.Count; y++)
            {
                if (((HiddenField)this.Table_ClaimDetailGrid.Rows[x].Cells[18].Controls[0]).Value.CompareTo(ItemsToDelete[y].ToString()) == 0)
                {
                    Removed = true;
                    this.Table_ClaimDetailGrid.Rows.RemoveAt(x);
                    break;
                }
            }

            if (!Removed)
            {
                x++;
            }
        }

        //reset the no.
        for (int z = 1; z < this.Table_ClaimDetailGrid.Rows.Count; z++)
        {
            Label lbl_no = (Label)this.Table_ClaimDetailGrid.Rows[z].Cells[1].Controls[0];
            lbl_no.Text = CurRow.ToString();
            CurRow++;
        }

        TimeSpan TimeDiff = new TimeSpan(DateTime.Now.Ticks - this.PageStartTime.Ticks);
        ViewState["mins"] = TimeDiff.Minutes;
        ViewState["secs"] = TimeDiff.Seconds;
        this.SetTimer();
    }
    #endregion

    #region Button_Save_Click
    protected void Button_Save_Click(object sender, EventArgs e)
    {
        if (this.SaveData(GonzalesClaimHeader.TypeOfClaimStatus.Draft))
        {
            // this is to monitor entire claim flow
            this.CurLogManager.LogAction(this.ClaimInternalID, this.CurrentPrivateSession.ActualLoginUser.InternalID, GonzalesUserAction.ClaimSaved, GonzalesClaimHeader.TypeOfClaimStatus.Submitted);
            Response.Redirect("GonzalesMyDraftDetail.aspx?id=" + this.ClaimInternalID);
        }

        this.SetTimer();

    }
    #endregion

    #region Button_Save_Exit_Click
    protected void Button_Save_Exit_Click(object sender, EventArgs e)
    {
        if (this.SaveData(GonzalesClaimHeader.TypeOfClaimStatus.Draft))
        {
            // this is to monitor entire claim flow
            this.CurLogManager.LogAction(this.ClaimInternalID, this.CurrentPrivateSession.ActualLoginUser.InternalID, GonzalesUserAction.ClaimSaved, GonzalesClaimHeader.TypeOfClaimStatus.Submitted);

            Response.Redirect("GonzalesMyDraft.aspx");
        }
    }
    #endregion

    #region Button_Submit_Click
    protected void Button_Submit_Click(object sender, EventArgs e)
    {
        TimeSpan TimeDiff = new TimeSpan(DateTime.Now.Ticks - this.PageStartTime.Ticks);
        ViewState["mins"] = TimeDiff.Minutes;
        ViewState["secs"] = TimeDiff.Seconds;
        this.SetTimer();

        // save first, as need to do data compare
        if (this.SaveData(GonzalesClaimHeader.TypeOfClaimStatus.Draft))
        {
            // check if got any claim detail
            if (this.ResultObj.ClaimDetails != null && this.ResultObj.ClaimDetails.Count > 0)
            {
                //check the claim date validation first
                if (this.ClaimDateValidation())
                {
                    // check if policy checked already done
                    if (this.AmountLimitValidation())
                    {
                        // submit mechanism
                        if (this.SaveData(GonzalesClaimHeader.TypeOfClaimStatus.Submitted))
                        {
                            // this is to monitor entire claim flow
                            this.CurLogManager.LogAction(this.ClaimInternalID, this.CurrentPrivateSession.ActualLoginUser.InternalID, GonzalesUserAction.ClaimSubmitted, GonzalesClaimHeader.TypeOfClaimStatus.Submitted);

                            #region Send email

                            if (GonzalesGeneralVariables.EmailActive)
                            {
                                string MailContent = "", MailTitle = "", ReceiverID = "";

                                if (this.ResultObj.NextApprover != null)
                                {
                                    using (EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.ClaimSubmitted, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
                                    {
                                        MailContent = CurMailGenerator.GenerateSubmittedClaimForApprover(
                                            this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName,
                                            this.CurrentPrivateSession.CurrentLoggedOnUser.EmployeeID,
                                            this.CurrentPrivateSession.CurrentLoggedOnUser.EmailID,
                                            this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.CompanyName,
                                            this.ResultObj.ClaimID,
                                            this.ResultObj.Reasons,
                                            this.ResultObj.LocalCurrency.InternalID + " " + this.ResultObj.TotalClaimedAmount,
                                            DateTime.Now.ToLongDateString(),
                                            GonzalesGeneralVariables.URL + "Default.aspx?redirect=" + ActionRedirect.SUBMITTED_CLAIM + "&id=" + this.ResultObj.InternalID + "&ad=" + this.ResultObj.NextApprover.EmailID);

                                        MailTitle = CurMailGenerator.MailTitle;
                                        ReceiverID = this.ResultObj.NextApprover.InternalID;
                                    }
                                }
                                else if (this.ResultObj.NextAuthorizer != null)
                                {
                                    using (EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.ClaimSubmitted, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
                                    {
                                        MailContent = CurMailGenerator.GenerateSubmittedClaimForApprover(
                                            this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName,
                                            this.CurrentPrivateSession.CurrentLoggedOnUser.EmployeeID,
                                            this.CurrentPrivateSession.CurrentLoggedOnUser.EmailID,
                                            this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.CompanyName,
                                            this.ResultObj.ClaimID,
                                            this.ResultObj.Reasons,
                                            this.ResultObj.LocalCurrency.InternalID + " " + this.ResultObj.TotalClaimedAmount,
                                            DateTime.Now.ToLongDateString(),
                                            GonzalesGeneralVariables.URL + "Default.aspx?redirect=" + ActionRedirect.SUBMITTED_CLAIM + "&id=" + this.ResultObj.InternalID + "&ad=" + this.ResultObj.NextAuthorizer.EmailID);

                                        MailTitle = CurMailGenerator.MailTitle;
                                        ReceiverID = this.ResultObj.NextAuthorizer.InternalID;
                                    }
                                }

                                if (MailContent.Length > 0)
                                {
                                    SystemUser Receiver = null;

                                    using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
                                    {
                                        Receiver = CurUserManager.GetUserByInternalID(ReceiverID);
                                    }

                                    if (Receiver != null)
                                    {
                                        using (EmailFactory CurEmailFactory = new EmailFactory(
                                            Receiver.DisplayName,
                                            Receiver.Email,
                                            MailTitle,
                                            MailContent))
                                        {
                                            if (Receiver.EmailID.ToLower().CompareTo("brian.king") != 0)
                                            {
                                                if (CurEmailFactory.IsReady)
                                                {
                                                    if (!CurEmailFactory.SendNow())
                                                    {
                                                        string LogID = SwissArmy.UniqueID();
                                                        this.CurLogManager.LogError(LogID, "[GonzalesMyDraftDetail.Button_Submit_Click] : Failed at CurEmailFactory.SendNow() : " + CurEmailFactory.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                                    }
                                                }
                                                else
                                                {
                                                    string LogID = SwissArmy.UniqueID();
                                                    this.CurLogManager.LogError(LogID, "[GonzalesMyDraftDetail.Button_Submit_Click] : Failed at CurEmailFactory Constructor : " + CurEmailFactory.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                                }
                                            }

                                            //Added by Agnes to send a copy of email to luikta.
                                            if (Receiver.EmailID.ToLower().Trim().CompareTo("paul.mauerman") == 0)
                                            {
                                                using (EmailFactory NewEmailFactory = new EmailFactory(
                                                    Receiver.DisplayName,
                                                    "Lukita.Utari@covidien.com",
                                                    MailTitle,
                                                    MailContent))
                                                {
                                                    if (CurEmailFactory.IsReady)
                                                    {

                                                        if (!NewEmailFactory.SendNow())
                                                        {
                                                            string LogID = SwissArmy.UniqueID();
                                                            this.CurLogManager.LogError(LogID, "[GonzalesMyDraftDetail.Button_Submit_Click] : Failed at CurEmailFactory.SendNow() : " + NewEmailFactory.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            #endregion

                            Response.Redirect("GonzalesMyClaimDetail.aspx?id=" + this.ClaimInternalID);
                        }
                    }
                    else
                    {
                        //this.ShowErrorMessage("Please enter some claim detail before submit");
                    }
                }             
            }
        }

    }
    #endregion

    #region Button_Continue_Click

    protected void Button_Continue_Click(object sender, EventArgs e)
    {
        // submit mechanism
        if (this.SaveData(GonzalesClaimHeader.TypeOfClaimStatus.Submitted))
        {
            // this is to monitor entire claim flow
            this.CurLogManager.LogAction(this.ClaimInternalID, this.CurrentPrivateSession.ActualLoginUser.InternalID, GonzalesUserAction.ClaimSubmitted, GonzalesClaimHeader.TypeOfClaimStatus.Submitted);

            #region Send email

            if (GonzalesGeneralVariables.EmailActive)
            {
                string MailContent = "", MailTitle = "", ReceiverID = "";

                if (this.ResultObj.NextApprover != null)
                {
                    using (EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.ClaimSubmitted, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
                    {
                        MailContent = CurMailGenerator.GenerateSubmittedClaimForApprover(
                            this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName,
                            this.CurrentPrivateSession.CurrentLoggedOnUser.EmployeeID,
                            this.CurrentPrivateSession.CurrentLoggedOnUser.EmailID,
                            this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.CompanyName,
                            this.ResultObj.ClaimID,
                            this.ResultObj.Reasons,
                            this.ResultObj.LocalCurrency.InternalID + " " + this.ResultObj.TotalClaimedAmount,
                            DateTime.Now.ToLongDateString(),
                            GonzalesGeneralVariables.URL + "Default.aspx?redirect=" + ActionRedirect.SUBMITTED_CLAIM + "&id=" + this.ResultObj.InternalID + "&ad=" + this.ResultObj.NextApprover.EmailID);

                        MailTitle = CurMailGenerator.MailTitle;
                        ReceiverID = this.ResultObj.NextApprover.InternalID;
                    }
                }
                else if (this.ResultObj.NextAuthorizer != null)
                {
                    using (EmailGenerator CurMailGenerator = new EmailGenerator(this.Server.MapPath(EmailTemplate.path) + EmailTemplate.ClaimSubmitted, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
                    {
                        MailContent = CurMailGenerator.GenerateSubmittedClaimForApprover(
                            this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName,
                            this.CurrentPrivateSession.CurrentLoggedOnUser.EmployeeID,
                            this.CurrentPrivateSession.CurrentLoggedOnUser.EmailID,
                            this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.CompanyName,
                            this.ResultObj.ClaimID,
                            this.ResultObj.Reasons,
                            this.ResultObj.LocalCurrency.InternalID + " " + this.ResultObj.TotalClaimedAmount,
                            DateTime.Now.ToLongDateString(),
                            GonzalesGeneralVariables.URL + "Default.aspx?redirect=" + ActionRedirect.SUBMITTED_CLAIM + "&id=" + this.ResultObj.InternalID + "&ad=" + this.ResultObj.NextAuthorizer.EmailID);

                        MailTitle = CurMailGenerator.MailTitle;
                        ReceiverID = this.ResultObj.NextAuthorizer.InternalID;
                    }
                }

                if (MailContent.Length > 0)
                {
                    SystemUser Receiver = null;

                    using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
                    {
                        Receiver = CurUserManager.GetUserByInternalID(ReceiverID);
                    }

                    using (EmailFactory CurEmailFactory = new EmailFactory(
                        Receiver.DisplayName,
                        Receiver.Email,
                        MailTitle,
                        MailContent))
                    {
                        if (Receiver.EmailID.ToLower().CompareTo("brian.king") != 0)
                        {
                            if (!CurEmailFactory.SendNow())
                            {
                                string LogID = SwissArmy.UniqueID();
                                this.CurLogManager.LogError(LogID, "[GonzalesMyDraftDetail.Button_Submit_Click] : Failed at CurEmailFactory.SendNow() : " + CurEmailFactory.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                            }
                        }
                    }

                    //Added by Agnes to send a copy of email to luikta.
                    if (Receiver.EmailID.ToLower().Trim().CompareTo("paul.mauerman") == 0)
                    {
                        using (EmailFactory NewEmailFactory = new EmailFactory(
                            Receiver.DisplayName,
                            "Lukita.Utari@covidien.com",
                            MailTitle,
                            MailContent))
                        {
                            if (NewEmailFactory.IsReady)
                            {

                                if (!NewEmailFactory.SendNow())
                                {
                                    string LogID = SwissArmy.UniqueID();
                                    this.CurLogManager.LogError(LogID, "[GonzalesMyDraftDetail.Button_Submit_Click] : Failed at CurEmailFactory.SendNow() : " + NewEmailFactory.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                }
                            }
                        }
                    }
                }
            }

            #endregion

            Response.Redirect("GonzalesMyClaimDetail.aspx?id=" + this.ClaimInternalID);
        }
        else
        {
            this.Label_Response.Text = "Submit Error";
        }
    }

    #endregion

    #region ImageButtonExpand_Click

    void ImageButtonExpand_Click(object sender, ImageClickEventArgs e)
    {                            
        string RowID = ((ImageButton)sender).ID.Substring(0, 36);
        int RowIndex = 0;

        // get the current row index
        for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
        {
            if (this.Table_ClaimDetailGrid.Rows[x].ID.CompareTo(RowID) == 0)
            {
                RowIndex = x;
                break;
            }
        }

        // check if claim type and local amount is selected
        //bool valid = (((DropDownList)this.Table_ClaimDetailGrid.Rows[RowIndex].Cells[1].Controls[0]).SelectedIndex > 0 && ((TextBox)this.Table_ClaimDetailGrid.Rows[RowIndex].Cells[12].Controls[0]).Text.CompareTo("0") != 0 && ((DropDownList)this.Table_ClaimDetailGrid.Rows[RowIndex].Cells[4].Controls[0]).SelectedIndex > 0 && ((TextBox)this.Table_ClaimDetailGrid.Rows[RowIndex].Cells[6].Controls[0]).Text.Length > 0);
        bool valid = (((DropDownList)this.Table_ClaimDetailGrid.Rows[RowIndex].Cells[2].Controls[0]).SelectedIndex > 0 && ((DropDownList)this.Table_ClaimDetailGrid.Rows[RowIndex].Cells[5].Controls[0]).SelectedIndex > 0 && ((TextBox)this.Table_ClaimDetailGrid.Rows[RowIndex].Cells[11].Controls[0]).Text.CompareTo("0.00") != 0 && ((TextBox)this.Table_ClaimDetailGrid.Rows[RowIndex].Cells[7].Controls[0]).Text.Length > 0);

        if (valid)
        {
            if (this.SaveData(GonzalesClaimHeader.TypeOfClaimStatus.Draft))
            {
                // save as draft first
                // redirect 
                Response.Redirect("GonzalesMyDraftDetailExpand.aspx?id=" + RowID + "&cid=" + this.ClaimInternalID);

            }
            else
            {                
               // this.ShowErrorMessage("Having error during save data");
            }
        }
        else
        {
            this.ShowErrorMessage(this.SaveDataError);
        }
    }

    #endregion

    #region DropDownList_SortBy_SelectedIndexChanged
    protected void DropDownList_SortBy_SelectedIndexChanged(object sender, EventArgs e)
    {
        //reset the curRow 
        CurRow = 1;

        // temporaly collect
        using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
        {
            this.ResultObj = CurClaimManager.GetClaimByInternalID(this.ClaimInternalID);

            if (this.ResultObj != null)
            {
                this.DetailDataCollection();

                #region Sorting Algorithm

                for (int x = (this.ResultObj.ClaimDetails.Count - 1); x > 0; x--)
                {
                    for (int y = 0; y < x; y++)
                    {
                        if (this.DropDownList_SortBy.SelectedValue.CompareTo("ExpenseDetail") == 0)
                        {
                            if (this.ResultObj.ClaimDetails[y].ClaimType.DisplayName.CompareTo(this.ResultObj.ClaimDetails[y + 1].ClaimType.DisplayName) > 0)
                            {
                                GonzalesClaimItem Tmp = (GonzalesClaimItem)this.ResultObj.ClaimDetails[y];
                                this.ResultObj.ClaimDetails[y] = this.ResultObj.ClaimDetails[y + 1];
                                this.ResultObj.ClaimDetails[y + 1] = Tmp;
                            }
                        }
                        else if (this.DropDownList_SortBy.SelectedValue.CompareTo("ClaimDate") == 0)
                        {
                            if (this.ResultObj.ClaimDetails[y].ClaimDate > this.ResultObj.ClaimDetails[y + 1].ClaimDate)
                            {
                                GonzalesClaimItem Tmp = (GonzalesClaimItem)this.ResultObj.ClaimDetails[y];
                                this.ResultObj.ClaimDetails[y] = this.ResultObj.ClaimDetails[y + 1];
                                this.ResultObj.ClaimDetails[y + 1] = Tmp;
                            }
                        }
                    }
                }

                #endregion

                // re-pump data
                // the table will be re-generate
                // the viewstate will re-deifined, however, the ID is still the same.
                this.Table_ClaimDetailGrid.Rows.Clear();
                this.BuiltTable();

                for (int x = 0; x < this.ActualNumberOfRow; x++)
                {
                    /*
                    if (x < this.ClaimDetailIDList.Count)
                    {
                        this.BuildRow(this.ClaimDetailIDList[x].ToString());
                    }
                    else
                    {
                        this.BuildRow();
                    }
                    */

                    if (x < this.ResultObj.ClaimDetails.Count)
                    {
                        this.BuildRow(this.ResultObj.ClaimDetails[x].InternalID);
                    }
                    else
                    {
                        this.BuildRow();
                    }
                }

                this.LoadIntoDetailGrid();
            }
            else
            {
                this.ShowErrorMessage(this.SortingError);
                this.CurLogManager.LogError("[GonzalesMyDraftDetail.DropDownList_SortBy_SelectedIndexChanged] : Failed at CurClaimManager.GetClaimByInternalID('" + this.ClaimInternalID + "') : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
            }
        }

        //TimeSpan TimeDiff = new TimeSpan(DateTime.Now.Ticks - this.PageStartTime.Ticks);
        //ViewState["mins"] = TimeDiff.Minutes;
        //ViewState["secs"] = TimeDiff.Seconds;
        //this.SetTimer();
        
    }
    #endregion

    #region Button_CreditCard_Click
    protected void Button_CreditCard_Click(object sender, EventArgs e)
    {
        if (this.SaveData(GonzalesClaimHeader.TypeOfClaimStatus.Draft))
        {
            // save as draft first
            // redirect 
            Response.Redirect("GonzalesCCImport.aspx?id=" + this.ClaimInternalID);

        }
        else
        {
            this.ShowErrorMessage(this.ErrorMessage);
        }
    }
    #endregion

    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {        
        this.Label_TotalAmount.Text += " (" + this.CurrentPrivateSession.CurrentLoggedOnUser.DefaultCurrency.InternalID + ")";
        this.TextBox_TotalAmount.Attributes["onclick"] = "NoEdit(this);";
        this.TextBox_TotalAmount.TabIndex = -1;
        this.TextBox_TotalAmount.CssClass = "DetailGridTextBoxNoEdit";
        this.TextBox_TotalAmount.Style.Add(HtmlTextWriterStyle.TextAlign, "right");
        this.TextBox_TotalAmount.Style.Add(HtmlTextWriterStyle.BorderStyle, "none");

        // owning box
        this.TextBox_Owning.CssClass = "DetailGridTextBoxNoEdit";
        this.TextBox_Owning.TabIndex = -1;
        this.TextBox_Owning.Style.Add(HtmlTextWriterStyle.TextAlign, "right");
        this.TextBox_Owning.Style.Add(HtmlTextWriterStyle.BorderStyle, "none");
        this.TextBox_Owning.Attributes["onclick"] = this.TextBox_Owning.Attributes["onfocus"] = "NoEdit(this);";

        // file upload
        this.Button_FileManager.Attributes["onclick"] = "ShowModal('FileManager', '', 'id=" + this.ClaimInternalID + "'); return false;";

        //dropdownlist for claimperiod
        this.DropDownList_ClaimPeriodMonth.Items.Add(new ListItem("", ""));
        this.DropDownList_ClaimPeriodMonth.Items.Add(new ListItem("1", "1"));
        this.DropDownList_ClaimPeriodMonth.Items.Add(new ListItem("2", "2"));
        this.DropDownList_ClaimPeriodMonth.Items.Add(new ListItem("3", "3"));
        this.DropDownList_ClaimPeriodMonth.Items.Add(new ListItem("4", "4"));
        this.DropDownList_ClaimPeriodMonth.Items.Add(new ListItem("5", "5"));
        this.DropDownList_ClaimPeriodMonth.Items.Add(new ListItem("6", "6"));
        this.DropDownList_ClaimPeriodMonth.Items.Add(new ListItem("7", "7"));
        this.DropDownList_ClaimPeriodMonth.Items.Add(new ListItem("8", "8"));
        this.DropDownList_ClaimPeriodMonth.Items.Add(new ListItem("9", "9"));
        this.DropDownList_ClaimPeriodMonth.Items.Add(new ListItem("10", "10"));
        this.DropDownList_ClaimPeriodMonth.Items.Add(new ListItem("11", "11"));
        this.DropDownList_ClaimPeriodMonth.Items.Add(new ListItem("12", "12"));

        //dropdownlist for claimperiod year
        string year = DateTime.Now.Year.ToString();
        string pyear = DateTime.Now.AddYears(-1).Year.ToString();
        string nyear = DateTime.Now.AddYears(1).Year.ToString();

        this.DropDownList_claimPeriodYear.Items.Add(new ListItem("", ""));
        this.DropDownList_claimPeriodYear.Items.Add(new ListItem(pyear, pyear));
        this.DropDownList_claimPeriodYear.Items.Add(new ListItem(year, year));
        this.DropDownList_claimPeriodYear.Items.Add(new ListItem(nyear, nyear));

        if (ResultObj != null)
        {
            if (ResultObj.ProjectedOn > DateTime.MinValue)
            {
                this.DropDownList_ClaimPeriodMonth.SelectedValue = ResultObj.ProjectedOn.Month.ToString();
                this.DropDownList_claimPeriodYear.SelectedValue = ResultObj.ProjectedOn.Year.ToString();
            }
        }

       
    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.Label_Remarks.Text = CurLanguageFactory.DisplayValue("Remarks");
                this.Label_ChequeNo.Text = CurLanguageFactory.DisplayValue("ChequeNo");
                this.Label_ClaimNum2.Text = CurLanguageFactory.DisplayValue("DateCreated");
                this.Label_ClaimPeriod.Text = CurLanguageFactory.DisplayValue("ClaimPeriod");
                this.Label_ElapsedTime.Text = CurLanguageFactory.DisplayValue("ElapsedTime");
                this.Label_EmployeeName.Text = CurLanguageFactory.DisplayValue("EmployeeName");
                this.Label_EmployeeNo.Text = CurLanguageFactory.DisplayValue("EmployeeNo");
                this.Label_EmployeeNo2.Text = CurLanguageFactory.DisplayValue("ApprovedBy");
                this.Label_IssuedBank.Text = CurLanguageFactory.DisplayValue("IssuedBank");
                this.Label_LastUpdate.Text = CurLanguageFactory.DisplayValue("LastUpdate");
                this.Label_OwningEmployee.Text = CurLanguageFactory.DisplayValue("OwningEmployee");
                this.Label_Purpose.Text = CurLanguageFactory.DisplayValue("Purpose");
                this.Label_Status.Text = CurLanguageFactory.DisplayValue("Status");
                this.Label_TotalAmount.Text = CurLanguageFactory.DisplayValue("TotalAmount");
                this.Label_TotalAmountLessPaid.Text = CurLanguageFactory.DisplayValue("TotalAmountLessPaid");
                this.Label2.Text = CurLanguageFactory.DisplayValue("Label2");
                this.Button_AddMore.Text = CurLanguageFactory.DisplayValue("AddMore");
                this.Button_Continue.Text = CurLanguageFactory.DisplayValue("Continue");
                this.Button_CreditCard.Text = CurLanguageFactory.DisplayValue("CreditCard");
                this.Button_FileManager.Text = CurLanguageFactory.DisplayValue("FileManager");
                this.Button_Remove.Text = CurLanguageFactory.DisplayValue("Remove");
                this.Button_Save.Text = CurLanguageFactory.DisplayValue("Save");
                this.Button_SavenExit.Text = CurLanguageFactory.DisplayValue("SavenExit");
                this.Button_Submit.Text = CurLanguageFactory.DisplayValue("Submit");

                this.ItemExpenseDetail = CurLanguageFactory.DisplayValue("ItemExpenseDetail");
                this.ItemClaimedDate = CurLanguageFactory.DisplayValue("ItemClaimedDate");
                this.ItemLocation = CurLanguageFactory.DisplayValue("ItemLocation");
                this.ItemReceiptNo = CurLanguageFactory.DisplayValue("ItemReceiptNo");
                this.ItemCreditCardDetail = CurLanguageFactory.DisplayValue("ItemCreditCardDetail");
                this.ItemClaimantRemarks = CurLanguageFactory.DisplayValue("ItemClaimantRemarks");
                this.ItemClaimedAmount = CurLanguageFactory.DisplayValue("ItemClaimedAmount");
                this.ItemTax = CurLanguageFactory.DisplayValue("ItemTax");
                this.ItemCurrency = CurLanguageFactory.DisplayValue("ItemCurrency");
                this.ItemExRate = CurLanguageFactory.DisplayValue("ItemExRate");
                this.ItemLocalAmount = CurLanguageFactory.DisplayValue("ItemLocalAmount");
                this.ItemProjectID = CurLanguageFactory.DisplayValue("ItemProjectID");

                // order by
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ItemOriginalOrder"), ""));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ItemExpenseDetail"), "ExpenseDetail"));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ItemClaimedDate"), "ClaimDate"));

                // buttons
                this.Button_CreditCard.Attributes["onclick"] = "return confirm('" + CurLanguageFactory.DisplayValue("PromptDataSave") + "');";
                this.Button_Remove.Attributes["onclick"] = "return confirm('" + CurLanguageFactory.DisplayValue("PromptDataDelete") + "');";
                this.Button_Save.Attributes["onclick"] = "return confirm('" + CurLanguageFactory.DisplayValue("PromptConfirmation") + "');";
                this.Button_SavenExit.Attributes["onclick"] = "return confirm('" + CurLanguageFactory.DisplayValue("PromptConfirmation") + "');";
                this.Button_Submit.Attributes["onclick"] = "return Validate('" + CurLanguageFactory.DisplayValue("ValidationText") + "');";                                

                // misc
                this.HeaderDeleteRemarks = CurLanguageFactory.DisplayValue("HeaderDeleteRemarks");
                this.ExpandLineItemConfirmation = CurLanguageFactory.DisplayValue("PromptExpandLineItem");
                this.ExpandLineItemToolTips = CurLanguageFactory.DisplayValue("HeaderExpandLineItemToolTips");
                this.ExchangeRateAlert = CurLanguageFactory.DisplayValue("PromptExchangeRateAlert");
                this.ValidationText = CurLanguageFactory.DisplayValue("ValidationText");

                // limit
                this.LimitAmount = CurLanguageFactory.DisplayValue("LimitAmount");
                this.LimitAmountTodate = CurLanguageFactory.DisplayValue("LimitAmountTodate");
                this.LimitExceed = CurLanguageFactory.DisplayValue("LimitExceed");
                this.LimitNo = CurLanguageFactory.DisplayValue("LimitNo");
                this.LimitPerHead = CurLanguageFactory.DisplayValue("LimitPerHead");
                this.LimitStrict = CurLanguageFactory.DisplayValue("LimitStrict");
                this.LimitYes = CurLanguageFactory.DisplayValue("LimitYes");

                this.ErrorMessage = CurLanguageFactory.DisplayValue("ErrorMessage");
                this.SortingError = CurLanguageFactory.DisplayValue("SortingError");
                this.SaveDataError = CurLanguageFactory.DisplayValue("SaveDataError");
                this.NoReceipt = CurLanguageFactory.DisplayValue("NoReceipt");
                this.PersonalExpense = CurLanguageFactory.DisplayValue("PersonalExpense");

                this.InvalidDateFormat = CurLanguageFactory.DisplayValue("InvalidDateFormat");
                this.ExpiryMessage1 = CurLanguageFactory.DisplayValue("ExpiryMessage1");
                this.ExpiryMessage2 = CurLanguageFactory.DisplayValue("ExpiryMessage2");
              
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesMyClaimDetail.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #region BuiltTable
    protected void BuiltTable()
    {
        // add all the table header
        TableRow HeaderRow = new TableRow();
        int CellCounter = 1;

        for (int x = 0; x < this.TotalColumns; x++)
        {
            HeaderRow.Cells.Add(new TableCell());
            HeaderRow.Cells[x].CssClass = "GridViewHeader";
        }

        // header for delete
        Image Image_DeleteHeader = new Image();
        Image_DeleteHeader.ImageUrl = GonzalesImages.Icon_Delete;
        Image_DeleteHeader.ToolTip = this.HeaderDeleteRemarks;
        HeaderRow.Cells[0].Controls.Add(Image_DeleteHeader);
        HeaderRow.Cells[0].HorizontalAlign = HorizontalAlign.Center;

        //Added by agnes[08march2009]-for enhancement
        HeaderRow.Cells[CellCounter++].Text = "No.";
        HeaderRow.Cells[CellCounter++].Text = this.ItemExpenseDetail; HeaderRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[CellCounter++].Text = ""; HeaderRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;    // credit card
        HeaderRow.Cells[CellCounter++].Text = ""; HeaderRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;    // is personal
        HeaderRow.Cells[CellCounter++].Text = this.ItemLocation; HeaderRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[CellCounter++].Text = this.ItemReceiptNo; HeaderRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[CellCounter++].Text = this.ItemClaimedDate; HeaderRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[CellCounter++].Text = ""; HeaderRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[CellCounter++].Text = this.ItemCreditCardDetail; HeaderRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[CellCounter++].Text = this.ItemClaimantRemarks; HeaderRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[CellCounter++].Text = this.ItemClaimedAmount; HeaderRow.Cells[CellCounter - 1].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[CellCounter++].Text = this.ItemTax; HeaderRow.Cells[CellCounter - 1].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[CellCounter++].Text = this.ItemCurrency; HeaderRow.Cells[CellCounter - 1].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[CellCounter++].Text = this.ItemExRate; HeaderRow.Cells[CellCounter - 1].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[CellCounter++].Text = this.ItemLocalAmount; HeaderRow.Cells[CellCounter - 1].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[CellCounter++].Text = "R"; HeaderRow.Cells[CellCounter - 1].HorizontalAlign = HorizontalAlign.Center; HeaderRow.Cells[CellCounter - 1].ToolTip = "Receipts?";
        HeaderRow.Cells[CellCounter++].Text = this.ItemProjectID; HeaderRow.Cells[CellCounter - 1].HorizontalAlign = HorizontalAlign.Center;
        HeaderRow.Cells[CellCounter++].Text = ""; HeaderRow.Cells[CellCounter - 1].HorizontalAlign = HorizontalAlign.Center;    // expand
        HeaderRow.Cells[CellCounter++].Visible = false; // warning, exceed limit indicator, always hide first

        this.Table_ClaimDetailGrid.Rows.Add(HeaderRow);
    }
    #endregion

    #region BuildRow

    protected void BuildRow()
    {        
        this.BuildRow(SwissArmy.UniqueID());
    }

    protected void BuildRow(string RowID)
    {
        TableRow NewTableRow = new TableRow();
        int CellCounter = 0;

        NewTableRow.ID = RowID;

        if (!this.ClaimDetailIDList.Contains(RowID))
        {
            this.ClaimDetailIDList.Add(NewTableRow.ID); // capture the row id using in the system
        }
        
        for (int x = 0; x < this.TotalColumns; x++)
        {
            // set default setting to all the row
            NewTableRow.Cells.Add(new TableCell());
            NewTableRow.Cells[x].CssClass = "GridViewItem";
            NewTableRow.Cells[x].HorizontalAlign = HorizontalAlign.Center;
        }

        #region 0. Delete Indicator

        CheckBox CheckBoxDelete = new CheckBox();
        CheckBoxDelete.ID = NewTableRow.ID + "_Delete";

        NewTableRow.Cells[CellCounter].Controls.Add(CheckBoxDelete);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(20);

        #endregion

        #region Extra Column to indicate the No.
        Label LabelNo = new Label();
        LabelNo.ID = NewTableRow.ID + "_No";
        LabelNo.Text = CurRow.ToString();
        CurRow++;

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(LabelNo);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(20);
        #endregion

        #region 1. Expense Detail / GL Account

        DropDownList DropDownClaimType = new DropDownList();
        DropDownClaimType.Width = Unit.Percentage(99);
        DropDownClaimType.CssClass = "FormDropDown";
        DropDownClaimType.ID = NewTableRow.ID + "_DropDownClaimType";
        DropDownClaimType.Attributes["onchange"] = "document.getElementById('" + NewTableRow.ID + "_TextBoxRemarks').value = ''; ExpenseDetailOnChange('" + this.ClaimInternalID + "', '" + NewTableRow.ID + "', this);";

        DropDownClaimType.Items.Add(new ListItem("", ""));
        for (int x = 0; x < this.ClaimTypes.Count; x++)
        {
            DropDownClaimType.Items.Add(new ListItem(this.ClaimTypes[x].DisplayName, this.ClaimTypes[x].InternalID));
        }

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(DropDownClaimType);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(250);

        #endregion

        #region 2. Claim Detail Type

        CellCounter++;
        HiddenField HiddenField_DetailType = new HiddenField();
        HiddenField_DetailType.ID = NewTableRow.ID + "_HiddenField_DetailType";
        HiddenField_DetailType.Value = "0";

        Image Image_DetailType = new Image();
        Image_DetailType.Visible = false;
        Image_DetailType.ID = NewTableRow.ID + "_Image_DetailType";

        NewTableRow.Cells[CellCounter].Controls.Add(HiddenField_DetailType);
        NewTableRow.Cells[CellCounter].Controls.Add(Image_DetailType);        
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(20);
        NewTableRow.Cells[CellCounter].Visible = this.ClaimHavingCreditCard; // by default

        #endregion

        #region 3. Is Personal

        CellCounter++;
        HiddenField HiddenField_IsPersonal = new HiddenField();
        HiddenField_IsPersonal.ID = NewTableRow.ID + "_HiddenField_IsPersonal";
        HiddenField_IsPersonal.Value = "0";

        Image Image_IsPersonal = new Image();
        Image_IsPersonal.Visible = false;        
        Image_IsPersonal.ID = NewTableRow.ID + "_Image_IsPersonal";

        NewTableRow.Cells[CellCounter].Controls.Add(HiddenField_IsPersonal);
        NewTableRow.Cells[CellCounter].Controls.Add(Image_IsPersonal);        
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(20);
        NewTableRow.Cells[CellCounter].Visible = this.ClaimHavingCreditCard; // by default

        #endregion

        #region 4. Country

        DropDownList DropDownCountry = new DropDownList();
        DropDownCountry.Width = Unit.Percentage(99);
        DropDownCountry.CssClass = "FormDropDown";
        DropDownCountry.ID = NewTableRow.ID + "_DropDownCountry";
        DropDownCountry.Attributes["onchange"] = "CountryOnChange(this);";

        DropDownCountry.Items.Add(new ListItem("", ""));
        for (int x = 0; x < this.Countries.Count; x++)
        {
            DropDownCountry.Items.Add(new ListItem(this.Countries[x].DisplayName, this.Countries[x].InternalID));
            if (this.DefaultCountryCode.Length > 0 && this.Countries[x].InternalID.CompareTo(this.DefaultCountryCode.Trim()) == 0)
            {
                DropDownCountry.Items[(DropDownCountry.Items.Count - 1)].Selected = true;
            }
        }

        //DropDownCountry.Items.FindByValue(this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.FromCountry.InternalID).Selected = true;

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(DropDownCountry);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(80);

        #endregion

        #region 5. City

        TextBox TextBoxCity = new TextBox();
        TextBoxCity.Width = Unit.Percentage(90);
        TextBoxCity.CssClass = "DetailGridTextBox";
        TextBoxCity.MaxLength = 20;
        TextBoxCity.ID = NewTableRow.ID + "_TextBoxCity";
        TextBoxCity.Attributes["onblur"] = "CheckReceipts(this, '" + NewTableRow.ID + "');";

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(TextBoxCity);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(80);

        #endregion

        #region 6. Date

        TextBox TextBoxDate = new TextBox();
        TextBoxDate.Width = Unit.Percentage(90);
        TextBoxDate.CssClass = "DetailGridTextBox";
        TextBoxDate.ID = NewTableRow.ID + "_TextBoxDate";
        //TextBoxDate.Attributes["onclick"] = "popUpCalendar(this, this, '" + SwissArmy.DateFormatForDisplay(this.CurrentPrivateSession.DateFormatInUse, "/") + "');";
       // TextBoxDate.Attributes["onfocus"] = "NoEdit(this);";
        TextBoxDate.Style.Add(HtmlTextWriterStyle.TextAlign, "center");


        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(TextBoxDate);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(80);

        HtmlButton imgDate = new HtmlButton();
        imgDate.ID = NewTableRow.ID + "_imgDate";
        imgDate.Style.Add("background", "url('img/calendar.gif')");
        imgDate.Style.Add("Width", "25px");                                              
        imgDate.Attributes.Add("onclick", "popUpCalendar(this, document.getElementById('" + NewTableRow.ID + "_TextBoxDate'),'" + SwissArmy.DateFormatForDisplay(this.CurrentPrivateSession.DateFormatInUse, "/") + "');");

        imgDate.Attributes["onfocus"] = "NoEdit(this);";
        imgDate.Attributes.Add("tabIndex", "-1");

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(imgDate);    

        #endregion

        #region 7. Description

        TextBox TextBoxDescription = new TextBox();
        TextBoxDescription.Width = Unit.Percentage(95);
        TextBoxDescription.CssClass = "DetailGridTextBox";
        TextBoxDescription.ID = NewTableRow.ID + "_TextBoxDescription";
        TextBoxDescription.MaxLength = 50;
        TextBoxDescription.Attributes["onclick"] = TextBoxDescription.Attributes["onfocus"] = "NoEdit(this);";
        TextBoxDescription.TabIndex = -1;

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(TextBoxDescription);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(150);

        #endregion

        #region 8. Remarks

        TextBox TextBoxRemarks = new TextBox();
        TextBoxRemarks.Width = Unit.Percentage(90);
        TextBoxRemarks.CssClass = "DetailGridTextBox";
        TextBoxRemarks.ID = NewTableRow.ID + "_TextBoxRemarks";
        TextBoxRemarks.MaxLength = 50;
        TextBoxRemarks.Attributes["onclick"] = "ExpenseDetailOnChange('" + this.ClaimInternalID + "', '" + NewTableRow.ID + "', document.getElementById('" + NewTableRow.ID + "_DropDownClaimType'));";

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(TextBoxRemarks);

        #endregion

        #region 9. Amount

        TextBox TextBoxAmount = new TextBox();
        TextBoxAmount.Width = Unit.Percentage(90);
        TextBoxAmount.CssClass = "DetailGridTextBox";
        TextBoxAmount.ID = NewTableRow.ID + "_TextBoxAmount";
        TextBoxAmount.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
        TextBoxAmount.Text = "0.00";
        //TextBoxAmount.Attributes["onload"] = "ExpenseDetailAmountValidation(document.getElementById('" + NewTableRow.ID + "_DropDownClaimType'), this);";
        TextBoxAmount.Attributes["onchange"] = "AmountBoxOnChange(this);";
        TextBoxAmount.Attributes["onfocus"] = TextBoxAmount.Attributes["onclick"] = "ExpenseDetailAmountValidation(document.getElementById('" + NewTableRow.ID + "_DropDownClaimType'), this);";

        if (this.Category == CategoryOfClaim.Entertainment)
            TextBoxAmount.TabIndex = -1;

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(TextBoxAmount);
        NewTableRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(80);

        #endregion

        #region 10. GST/VAT

        TextBox TextBoxGSTVAT = new TextBox();
        TextBoxGSTVAT.Width = Unit.Percentage(90);        
        TextBoxGSTVAT.ID = NewTableRow.ID + "_TextBoxGSTVAT";
        TextBoxGSTVAT.Text = this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.FromCountry.Tax.ToString();        
        TextBoxGSTVAT.Style.Add(HtmlTextWriterStyle.TextAlign, "center");

        if (!this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.UsingVAT)
        {
            // if not using VAT, lock it
            TextBoxGSTVAT.Attributes["onclick"] = "NoEdit(this);";
            TextBoxGSTVAT.CssClass = "DetailGridTextBoxNoEdit";
            TextBoxGSTVAT.Enabled = false;
            TextBoxGSTVAT.TabIndex = -1;
        }
        else
        {
            TextBoxGSTVAT.Attributes["onchange"] = "VATBoxOnChange(this);";
            TextBoxGSTVAT.CssClass = "DetailGridTextBox";
        }

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(TextBoxGSTVAT);
        NewTableRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(60);

        #endregion

        #region 11. Currency

        // drop down, default
        DropDownList DropDownCurrency = new DropDownList();
        DropDownCurrency.Width = Unit.Percentage(99);
        DropDownCurrency.CssClass = "FormDropDown";
        DropDownCurrency.ID = NewTableRow.ID + "_DropDownCurrency";
        DropDownCurrency.Attributes["onChange"] = "CurrencyOnChange(this);";

        for (int x = 0; x < this.Currencies.Count; x++)
        {
            DropDownCurrency.Items.Add(new ListItem(this.Currencies[x].InternalID, this.Currencies[x].InternalID));
            if (this.DefaultCurrencyCode.Length > 0 && this.Currencies[x].InternalID.CompareTo(this.DefaultCurrencyCode) == 0)
            {
                DropDownCurrency.Items[(DropDownCurrency.Items.Count - 1)].Selected = true;
            }
        }
        //DropDownCurrency.Items.FindByValue(this.CurrentPrivateSession.CurrentLoggedOnUser.DefaultCurrency.InternalID).Selected = true;

        // 2nd option, default is hidden
        TextBox TextBox_Currency = new TextBox();
        TextBox_Currency.ID = NewTableRow.ID + "_TextBoxCurrency";
        TextBox_Currency.CssClass = "DetailGridTextBoxNoEdit";
        TextBox_Currency.TabIndex = -1;
        TextBox_Currency.Attributes["onClick"] = TextBox_Currency.Attributes["onFocus"] = "NoEdit(this);";        
        TextBox_Currency.Width = Unit.Percentage(90);
        TextBox_Currency.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
        TextBox_Currency.Visible = false;
        
        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(DropDownCurrency);
        NewTableRow.Cells[CellCounter].Controls.Add(TextBox_Currency);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(50);
        NewTableRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 12. ExRate

        TextBox TextBoxExRate = new TextBox();
        TextBoxExRate.Width = Unit.Percentage(90);
        TextBoxExRate.CssClass = "DetailGridTextBox";
        TextBoxExRate.ID = NewTableRow.ID + "_TextBoxExRate";
        TextBoxExRate.Text = this.DefaultExchangeRate.ToString();
        TextBoxExRate.Attributes["onchange"] = "ExchangeRateBoxOnChange(this, '" + this.ExchangeRateAlert + "');";
        TextBoxExRate.Style.Add(HtmlTextWriterStyle.TextAlign, "center");

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(TextBoxExRate);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(50);

        #endregion

        #region 13. Local Amount

        TextBox TextBoxLocalAmount = new TextBox();
        TextBoxLocalAmount.Width = Unit.Percentage(90);
        TextBoxLocalAmount.CssClass = "DetailGridTextBoxNoEdit";
        TextBoxLocalAmount.ID = NewTableRow.ID + "_TextBoxLocalAmount";
        TextBoxLocalAmount.Text = "0.00";
        TextBoxLocalAmount.Style.Add(HtmlTextWriterStyle.TextAlign, "center");
        TextBoxLocalAmount.Attributes["onfocus"] = TextBoxLocalAmount.Attributes["onclick"] = "NoEdit(this);";
        TextBoxLocalAmount.TabIndex = -1;

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(TextBoxLocalAmount);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(80);

        #endregion

        #region 14. Receipts

        CheckBox CheckBoxReceipts = new CheckBox();
        CheckBoxReceipts.ID = NewTableRow.ID + "_CheckBoxReceipts";

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(CheckBoxReceipts);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(30);
        NewTableRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 15. Project ID

        TextBox TextBoxProjectID = new TextBox();
        TextBoxProjectID.Width = Unit.Percentage(90);
        TextBoxProjectID.CssClass = "DetailGridTextBox";
        TextBoxProjectID.ID = NewTableRow.ID + "_TextBoxProjectID";
        TextBoxProjectID.Attributes["onclick"] = "ShowModal('ProjectBrowser', this, ''); return false;"; ;

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(TextBoxProjectID);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(60);

        #endregion

        #region 16. Expand

        HiddenField HiddenField_Parent = new HiddenField();
        HiddenField_Parent.ID = NewTableRow.ID + "_HiddenField_Parent";

        ImageButton ImageButtonExpand = new ImageButton();
        ImageButtonExpand.ImageUrl = GonzalesImages.Icon_Expand;
        ImageButtonExpand.ID = NewTableRow.ID + "_ImageButtonExpand";
        ImageButtonExpand.Attributes["onClick"] = "return confirm('" + this.ExpandLineItemConfirmation + "');";
        ImageButtonExpand.ToolTip = this.ExpandLineItemToolTips;
        ImageButtonExpand.Click += new ImageClickEventHandler(ImageButtonExpand_Click);

        CellCounter++;
        NewTableRow.Cells[CellCounter].Controls.Add(HiddenField_Parent);
        NewTableRow.Cells[CellCounter].Controls.Add(ImageButtonExpand);
        NewTableRow.Cells[CellCounter].Width = Unit.Pixel(20);
        NewTableRow.Cells[CellCounter].HorizontalAlign = HorizontalAlign.Center;

        #endregion

        #region 17. Warning

        // initially this column shd hide

        #endregion

        // done
        this.Table_ClaimDetailGrid.Rows.Add(NewTableRow);        
        this.ClaimDetailRowBuiltCounter++;
    }

    #endregion

    #region TableGridComponengtSetup
    protected void TableGridComponengtSetup()
    {
        if (!this.IsComponentSetup)
        {
            // country
            using (CountryManager CurCountryManager = new CountryManager(this.CurrentPrivateSession))
            {
                this.Countries = CurCountryManager.GetAllCountry();                

                if (this.Countries != null)
                {
                    for (int x = (this.Countries.Count - 1); x > 0; x--)
                    {
                        for (int y = 0; y < x; y++)
                        {
                            if (this.Countries[y].DisplayName.CompareTo(this.Countries[y + 1].DisplayName) > 0)
                            {
                                Country Tmp = (Country)this.Countries[y];
                                this.Countries[y] = this.Countries[y + 1];
                                this.Countries[y + 1] = Tmp;
                            }
                        }
                    }
                }
            }

            // currency
            using (CurrencyManager CurCurrencyManager = new CurrencyManager(this.CurrentPrivateSession))
            {
                this.Currencies = CurCurrencyManager.GetAllCurrency();
                
                if (this.Currencies != null)
                {
                    for (int x = (this.Currencies.Count - 1); x > 0; x--)
                    {
                        for (int y = 0; y < x; y++)
                        {
                            if (this.Currencies[y].DisplayName.CompareTo(this.Currencies[y + 1].DisplayName) > 0)
                            {
                                Currency Tmp = (Currency)this.Currencies[y];
                                this.Currencies[y] = this.Currencies[y + 1];
                                this.Currencies[y + 1] = Tmp;
                            }
                        }
                    }
                   
                }
            }

            // claim type
            using (GLClaimTypeManager CurGLClaimTypeManager = new GLClaimTypeManager(this.CurrentPrivateSession))
            {
                this.ClaimTypes = CurGLClaimTypeManager.GetActiveClaimTypeInLangByEntity(
                    this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage,
                    this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.Entity,
                    ClaimManager.GetClaimCategoryInCode(this.Category).ToString());
                
                if (this.ClaimTypes != null)
                {
                    if (this.ClaimTypes != null)
                    {
                        for (int x = (this.ClaimTypes.Count - 1); x > 0; x--)
                        {
                            for (int y = 0; y < x; y++)
                            {
                                if (this.ClaimTypes[y].DisplayName.CompareTo(this.ClaimTypes[y + 1].DisplayName) > 0)
                                {
                                    GLClaimType Tmp = (GLClaimType)this.ClaimTypes[y];
                                    this.ClaimTypes[y] = this.ClaimTypes[y + 1];
                                    this.ClaimTypes[y + 1] = Tmp;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
    }
    #endregion

    #region SetTimer
    protected void SetTimer()
    {
        int minutes = 0, seconds = 0, interval = 15;
        string min = "0", sec = "0";
        int IsNew = 1;

        if (ViewState["mins"] != null)
        {
            minutes = Convert.ToInt32(ViewState["mins"]);
            seconds = Convert.ToInt32(ViewState["secs"]);
            IsNew = 0;
        }

        if (minutes == 0 && seconds == 0)
            this.PageStartTime = DateTime.Now;

        interval = Convert.ToInt32(GonzalesGeneralVariables.ElapsedTime);
        //if (this.CurPrivateConfig.LoginProjectProfile.ProjectTimeLeft.ToString().IndexOf(".") > 0)
        //{
        //    string[] TimeRecorded = SwissArmy.StringSplit(this.CurPrivateConfig.LoginProjectProfile.ProjectTimeLeft.ToString(), ".");
        //    minutes = Convert.ToInt32(TimeRecorded[0]);
        //    seconds = Convert.ToInt32((Convert.ToDecimal(TimeRecorded[1]) / 100) * 60);
        //}
        //else
        //{
        //    minutes = Convert.ToInt32(this.CurPrivateConfig.LoginProjectProfile.ProjectTimeLeft);
        //}

        if (minutes < 10)
            min = min + minutes.ToString();
        else
            min = minutes.ToString();
        if (seconds < 10)
            sec = sec + seconds.ToString();
        else
            sec = seconds.ToString();

        this.LabelValue_ElapsedTime.Text = min + ":" + sec;
        this.js_TimeVariable(minutes, seconds, interval, IsNew);
    }
    #endregion

    #endregion

    #region Data Operation

    #region LoadData
    protected void LoadData()
    {
        if (Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36)
        {
            this.ClaimInternalID = Request.QueryString["id"];

            using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
            {
                ResultObj = CurClaimManager.GetClaimByInternalID(this.ClaimInternalID);

                if (ResultObj != null)
                {
                    //this.LabelValue_Approver.Text = (this.CurrentPrivateSession.CurrentLoggedOnUser.PersonnelReportTo != null) ? this.CurrentPrivateSession.CurrentLoggedOnUser.PersonnelReportTo.DisplayName : ""; // is only draft, hence the approver is immediate supervisor                    
                    this.LabelValue_EmployeeName.Text = this.CurrentPrivateSession.CurrentLoggedOnUser.DisplayName + "(" + this.CurrentPrivateSession.CurrentLoggedOnUser.EmailID + ")"; 
                    this.LabelValue_EmployeeNo.Text = this.CurrentPrivateSession.CurrentLoggedOnUser.EmployeeID;
                    this.LabelValue_CreatedDate.Text = SwissArmy.DateConvert(ResultObj.CreatedOn, this.CurrentPrivateSession.DateFormatInUse, "/");                    
                    this.LabelValue_Status.Text = ClaimManager.GetClaimStatusInString(ResultObj.Status);
                    this.TextBox_Reasons.Text = ResultObj.Reasons;

                    // load default
                    this.DefaultCountryCode = ResultObj.DefaultCountryCode;
                    this.DefaultCurrencyCode = ResultObj.DefaultCurrencyCode;
                    this.DefaultExchangeRate = ResultObj.DefaultExchangeRate;

                    //added by agnes for last saved datetime
                    this.LabelValue_LastUpdate.Text = SwissArmy.DateConvert(ResultObj.LastUpdatedOn,this.CurrentPrivateSession.DateFormatInUse,"/") + " " + ResultObj.LastUpdatedOn.ToString("HH:mm:ss");

                    // load the items
                    this.ResultObj.ClaimDetails = CurClaimManager.GetClaimItemsByClaimHeader(this.ClaimInternalID);
                    if (this.ResultObj.ClaimDetails == null)
                    {                 
                        this.CurLogManager.LogMessage("[GonzalesMyDraftDetail : LoadData] : CurClaimManager.GetClaimItemsByClaimHeader(" + this.ClaimInternalID + ") : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);

                        // redirect
                    }

                    #region show the approver

                    SystemUser Approver = null;

                    if (this.CurrentPrivateSession.CurrentLoggedOnUser.AppRoute == ApprovingRoute.Normal)
                    {
                        Approver = this.CurrentPrivateSession.CurrentLoggedOnUser.PersonnelReportTo;
                    }
                    else if (this.CurrentPrivateSession.CurrentLoggedOnUser.AppRoute == ApprovingRoute.MultiLevel)
                    {
                        Approver = this.CurrentPrivateSession.CurrentLoggedOnUser.PersonnelReportTo;
                    }
                    else if (this.CurrentPrivateSession.CurrentLoggedOnUser.AppRoute == ApprovingRoute.Exception)
                    {
                        using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
                        {
                            SystemUsers Approvers = CurUserManager.GetExceptionalApproversMatrix(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);
                            if (Approvers != null && Approvers.Count > 0)
                            {
                                Approver = Approvers[0];
                            }
                        }
                    }

                    if (Approver != null)
                    {
                        this.LabelValue_Approver.Text = Approver.DisplayName;
                    }                    

                    #endregion

                }
                else
                {
                    // log reasons
                }

            }

            #region Supporting Documents

            using (FileManager CurFileManager = new FileManager(this.CurrentPrivateSession))
            {
                SupportingDocuments ListOfDocs = CurFileManager.GetFilesByClaimID(this.ClaimInternalID);
                if (ListOfDocs != null)
                {
                    this.Button_FileManager.Text += " (" + ListOfDocs.Count + ")";
                }
                else
                {
                    this.Button_FileManager.Text += " (0)";

                    string ErrorID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(ErrorID, "[GonzalesMyClaimDetail.LoadData] : Failed at CurFileManager.GetFilesByClaimID(" + this.ClaimInternalID + ") : " + CurFileManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
            }

            #endregion
        }
    }
    #endregion  
  
    #region LoadIntoDetailGrid
    protected void LoadIntoDetailGrid()
    {
        this.ClaimHavingCreditCard = false;
        int TotalCurrentRow = this.Table_ClaimDetailGrid.Rows.Count - 1;
        int ExtraRowNeeded = (this.ResultObj.ClaimDetails.Count > TotalCurrentRow) ? (this.ResultObj.ClaimDetails.Count - TotalCurrentRow) : 0;

        for (int x = 0; x < ExtraRowNeeded; x++)
        {
            // built extra row to cater current claim detail
            this.BuildRow();
        }

        // load into grid now
        for (int x = 0; x < this.ResultObj.ClaimDetails.Count; x++)
        {
            TableRow CurrentRow = this.Table_ClaimDetailGrid.Rows[(x+1)];
            GonzalesClaimItem CurClaimItem = (GonzalesClaimItem)this.ResultObj.ClaimDetails[x];
            int CellCounter = 0;
        
            // By determining if the claimant is using cash or credit card, we will able to know which data can be edited,
            // and which can't. Credit Card data are from other sources, hence can't be edited, except certain data, like
            // claim type, country...etc            
            bool UsingCash = (CurClaimItem.ClaimDetailType == TypeOfClaimDetail.Cash);  // for individual row
            this.ClaimHavingCreditCard = (CurClaimItem.ClaimDetailType == TypeOfClaimDetail.CreditCard) ? true : ClaimHavingCreditCard; // for entire claim row

            #region 0. Delete Indicator

            if (CurClaimItem.ParentID.Length > 0)
            {
                // only parents able to delete                
                CurrentRow.Cells[CellCounter].Controls[0].Visible = false;
            }

            #endregion

            #region Extra Column to indicate the No.

            CellCounter++;
            Label labelNo = (Label)CurrentRow.Cells[CellCounter].Controls[0];
            labelNo.Text = NewRow.ToString();
            NewRow++;

            #endregion

            #region 1. Expense Detail / GL Account

            CellCounter++;
            DropDownList DropDownClaimType = null;
            if (CurClaimItem.ClaimType != null)
            {
                DropDownClaimType = (DropDownList)CurrentRow.Cells[CellCounter].Controls[0];
                DropDownClaimType.SelectedItem.Selected = false;

                if (DropDownClaimType.Items.FindByValue(this.ResultObj.ClaimDetails[x].ClaimType.InternalID) != null) {
                    DropDownClaimType.Items.FindByValue(this.ResultObj.ClaimDetails[x].ClaimType.InternalID).Selected = true;

                } else {

                    using (GLClaimTypeManager CurClaimTypeManager = new GLClaimTypeManager(this.CurrentPrivateSession))
                    {
                        MasterBaseCollection ClaimTypesCollection = CurClaimTypeManager.GetAllClaimTypeInLang(this.CurrentPrivateSession.ActualLoginUser.PreferedLanguage);

                        if (ClaimTypesCollection != null)
                        {
                            for (int y = 0; y < ClaimTypesCollection.Count; y++)
                            {
                                if (ClaimTypesCollection[y].InternalID.CompareTo(CurClaimItem.ClaimType.InternalID) == 0)
                                {
                                    CurClaimItem.Remarks = "'" + ClaimTypesCollection[y].DisplayName + "' is no longer avalaible.";
                                }
                            }
                        }
                    }
                }                           
            }
            else
            {
                DropDownClaimType.SelectedItem.Selected = false;
            }

            #endregion

            #region 2. Claim Detail Type

            CellCounter++;

            HiddenField HiddenField_DetailType = (HiddenField)this.Table_ClaimDetailGrid.Rows[(x + 1)].Cells[CellCounter].Controls[0];
            HiddenField_DetailType.Value = ClaimManager.GetClaimDetailTypeInCode(CurClaimItem.ClaimDetailType).ToString();

            if (CurClaimItem.ClaimDetailType == TypeOfClaimDetail.CreditCard)
            {
                Image Image_CreditCard = (Image)this.Table_ClaimDetailGrid.Rows[(x + 1)].Cells[CellCounter].Controls[1];
                Image_CreditCard.ImageUrl = GonzalesImages.Icon_CreditCard;
                Image_CreditCard.ToolTip = CurClaimItem.Description;
                Image_CreditCard.Visible = true;
            }

            #endregion

            #region 3. Is Personal

            CellCounter++;

            HiddenField HiddenField_IsPersonal = (HiddenField)this.Table_ClaimDetailGrid.Rows[(x + 1)].Cells[CellCounter].Controls[0];
            HiddenField_IsPersonal.Value = CurClaimItem.IsPersonnal ? "1" : "0";

            if (CurClaimItem.IsPersonnal)
            {
                Image ImageIsPersonal = (Image)this.Table_ClaimDetailGrid.Rows[(x + 1)].Cells[CellCounter].Controls[1];
                ImageIsPersonal.ImageUrl = GonzalesImages.Icon_Personal;
                ImageIsPersonal.Visible = true;
                
            }
                         
            #endregion

            #region 4. Country

            CellCounter++;
            DropDownList DropDownCountry = null;
            if (CurClaimItem.Country != null)
            {
                DropDownCountry = (DropDownList)CurrentRow.Cells[CellCounter].Controls[0];
                DropDownCountry.SelectedItem.Selected = false;
                DropDownCountry.Items.FindByValue(CurClaimItem.Country.InternalID).Selected = true;
            }
            else
            {
                DropDownCountry.SelectedItem.Selected = false;
            }

            #endregion

            #region 5. City

            CellCounter++;
            if (CurClaimItem.City.Length > 0)
            {
                TextBox TextBoxCity = (TextBox)CurrentRow.Cells[CellCounter].Controls[0];
                TextBoxCity.Text = CurClaimItem.City;
            }

            #endregion

            #region 6. Date

            CellCounter++;
            if (CurClaimItem.ClaimDate != DateTime.MinValue)
            {
                TextBox TextBoxClaimDate = (TextBox)CurrentRow.Cells[CellCounter].Controls[0];
                TextBoxClaimDate.Text = SwissArmy.DateConvert(CurClaimItem.ClaimDate, this.CurrentPrivateSession.DateFormatInUse, "/");

                //CellCounter++;
                HtmlButton imgDate = (HtmlButton)CurrentRow.Cells[CellCounter + 1].Controls[0];

                if (!UsingCash)
                {
                    TextBoxClaimDate.CssClass = "DetailGridTextBoxNoEdit";
                    TextBoxClaimDate.TabIndex = -1;
                    TextBoxClaimDate.Attributes["onClick"] = TextBoxClaimDate.Attributes["onFocus"] = "NoEdit(this);";
                    imgDate.Disabled = true;
                }
            }
            CellCounter++;

            #endregion

            #region 7. Description

            CellCounter++;
            if (CurClaimItem.Description.Length > 0)
            {
                TextBox TextBoxDescription = (TextBox)CurrentRow.Cells[CellCounter].Controls[0];
                TextBoxDescription.Text = CurClaimItem.Description;
                TextBoxDescription.ToolTip = CurClaimItem.Description;

                if (!UsingCash)
                {
                    TextBoxDescription.CssClass = "DetailGridTextBoxNoEdit";
                    TextBoxDescription.TabIndex = -1;
                    TextBoxDescription.Attributes["onFocus"] = "NoEdit(this);";
                }
            }

            #endregion

            #region 8. Remarks

            CellCounter++;
            if (CurClaimItem.Remarks.Length > 0)
            {
                TextBox TextBoxRemarks = (TextBox)CurrentRow.Cells[CellCounter].Controls[0];
                TextBoxRemarks.Text = CurClaimItem.Remarks;
                TextBoxRemarks.ToolTip = CurClaimItem.Remarks;
            }

            #endregion

            #region 9. Amount claimed

            CellCounter++;

            TextBox TextBoxAmountClaimed = (TextBox)CurrentRow.Cells[CellCounter].Controls[0];

            if (CurClaimItem.ClaimedAmount > 0)
            {
                TextBoxAmountClaimed.Text = CurClaimItem.ClaimedAmount.ToString();

                if (!UsingCash)
                {
                    TextBoxAmountClaimed.CssClass = "DetailGridTextBoxNoEdit";
                    TextBoxAmountClaimed.TabIndex = -1;
                    TextBoxAmountClaimed.Attributes["onFocus"] = "NoEdit(this);";                    
                }
            }

            #endregion

            #region 10. GST/TAX

            CellCounter++;
            TextBox TextBoxGSTVAT = (TextBox)CurrentRow.Cells[CellCounter].Controls[0];
            TextBoxGSTVAT.Text = CurClaimItem.Tax.ToString();

            if (!UsingCash)
            {
                TextBoxGSTVAT.CssClass = "DetailGridTextBoxNoEdit";
                TextBoxGSTVAT.TabIndex = -1;
                TextBoxGSTVAT.Attributes["onClick"] = TextBoxGSTVAT.Attributes["onFocus"] = "NoEdit(this);";
            }

            #endregion

            #region 11. Currency

            CellCounter++;
            if (UsingCash)
            {   // if using cash
                DropDownList DropDownCurrency = null;
                if (CurClaimItem.ExchangeCurrency != null)
                {
                    DropDownCurrency = (DropDownList)CurrentRow.Cells[CellCounter].Controls[0];
                    DropDownCurrency.SelectedItem.Selected = false;
                    DropDownCurrency.Items.FindByValue(CurClaimItem.ExchangeCurrency.InternalID).Selected = true;
                }
                else
                {
                    DropDownCurrency.SelectedItem.Selected = false;
                }
            }
            else
            {
                // clear the previous control
                CurrentRow.Cells[CellCounter].Controls[0].Visible = false;

                TextBox TextBox_Currency = (TextBox)CurrentRow.Cells[CellCounter].Controls[1];
                TextBox_Currency.Text = CurClaimItem.ClaimedAmountCurrency.InternalID;
                TextBox_Currency.Visible = true;
            }

            #endregion

            #region 12. ExRate

            CellCounter++;

            if (CurClaimItem.ExchangeRate > 0)
            {
                TextBox TextBoxExRate = (TextBox)CurrentRow.Cells[CellCounter].Controls[0];
                TextBoxExRate.Text = Convert.ToDecimal(CurClaimItem.ExchangeRate).ToString();

                if (!UsingCash)
                {
                    TextBoxExRate.CssClass = "DetailGridTextBoxNoEdit";
                    TextBoxExRate.TabIndex = -1;
                    TextBoxExRate.Attributes["onFocus"] = "NoEdit(this);";
                }
            }

            #endregion

            #region 13. Amount Out

            CellCounter++;
            if (CurClaimItem.AmountOut > 0)
            {
                TextBox TextBoxAmountOut = (TextBox)CurrentRow.Cells[CellCounter].Controls[0];
                TextBoxAmountOut.Text = decimal.Parse(CurClaimItem.AmountOut.ToString()).ToString(GonzalesGeneralVariables.CurrencyFormat);
            }

            #endregion

            #region 14. Receitps

            CellCounter++;

            CheckBox CheckBoxHavingReceipts = (CheckBox)CurrentRow.Cells[CellCounter].Controls[0];
            CheckBoxHavingReceipts.Checked = CurClaimItem.HavingReceipts;
                
            #endregion

            #region 15. Project ID
            
            CellCounter++;
            if (CurClaimItem.ProjectID.Length > 0)
            {
                TextBox TextBoxProjectID = (TextBox)CurrentRow.Cells[CellCounter].Controls[0];
                TextBoxProjectID.Text = CurClaimItem.ProjectID;
            }

            #endregion

            #region 16. Expand

            CellCounter++;
            if (CurClaimItem.ParentID.Length > 0)
            {   
                HiddenField HiddenField_Parent = (HiddenField)CurrentRow.Cells[CellCounter].Controls[0];
                HiddenField_Parent.Value = CurClaimItem.ParentID;

                // only parents able to expand, hence need to hide expand button for those non-parent                
                CurrentRow.Cells[CellCounter].Controls[1].Visible = false;

            }

            #endregion

            CurrentRow.Cells[11].Controls[0].Focus();

        }

        //loading the projected date

        if (ResultObj.ProjectedOn != DateTime.MinValue)
        {
            this.DropDownList_ClaimPeriodMonth.SelectedValue = ResultObj.ProjectedOn.Month.ToString();
            this.DropDownList_claimPeriodYear.SelectedValue = ResultObj.ProjectedOn.Year.ToString();
        }
        //else
        //{
        //    this.DropDownList_ClaimPeriodMonth.SelectedValue = Convert.ToString(DateTime.Now.Month - 1);
        //    this.DropDownList_claimPeriodYear.SelectedValue = DateTime.Now.Year.ToString();
        //}

        #region Datagrid Column Setting

        for (int x = 0; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
        {
            this.Table_ClaimDetailGrid.Rows[x].Cells[3].Visible = this.Table_ClaimDetailGrid.Rows[x].Cells[4].Visible = ClaimHavingCreditCard;            
        }

        #endregion
    }

    #endregion

    #region SaveData
    protected bool SaveData(GonzalesClaimHeader.TypeOfClaimStatus CurrentStatus)
    {
        bool smooth = true;

        using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
        {

            this.ResultObj = CurClaimManager.GetClaimByInternalID(this.ClaimInternalID);
            if (this.ResultObj != null)
            {
                if (this.ResultObj.Status != GonzalesClaimHeader.TypeOfClaimStatus.Draft && this.ResultObj.Status != GonzalesClaimHeader.TypeOfClaimStatus.New)
                {
                    smooth = false;
                    ShowErrorMessage("Your claim has been submitted to your Approvers. If you have submitted the claim by mistake, kindly contact your Approvers and ask them to reject the claim.");
                }
                else
                {
                    // collect data for header
                    this.ResultObj.Reasons = this.TextBox_Reasons.Text;
                    this.ResultObj.LastUpdatedBy = this.CurrentPrivateSession.CurrentLoggedOnUser;
                    this.ResultObj.LastUpdatedOn = DateTime.Now;
                    this.ResultObj.Status = CurrentStatus;

                    if (this.DropDownList_ClaimPeriodMonth.SelectedItem.Value != "" && this.DropDownList_claimPeriodYear.SelectedItem.Value != "")
                    {
                        string claimperiod = "1/" + this.DropDownList_ClaimPeriodMonth.SelectedItem.Value + "/" + this.DropDownList_claimPeriodYear.SelectedItem.Value;
                        if (this.CurrentPrivateSession.DateFormatInUse.ToString().CompareTo("MMDDYYYY") == 0)
                            claimperiod = this.DropDownList_ClaimPeriodMonth.SelectedItem.Value + "/" + "1/" + this.DropDownList_claimPeriodYear.SelectedItem.Value;
                        if (this.CurrentPrivateSession.DateFormatInUse.ToString().CompareTo("YYYYMMDD") == 0)
                            claimperiod = this.DropDownList_claimPeriodYear.SelectedItem.Value + "/" + this.DropDownList_ClaimPeriodMonth.SelectedItem.Value + "/" + "1";
                        if (this.CurrentPrivateSession.DateFormatInUse.ToString().CompareTo("YYYYDDMM") == 0)
                            claimperiod = this.DropDownList_claimPeriodYear.SelectedItem.Value + "/" + "1/" +this.DropDownList_ClaimPeriodMonth.SelectedItem.Value;
                        //this.ResultObj.ProjectedOn = DateTime.Parse(claimperiod);
                        this.ResultObj.ProjectedOn = SwissArmy.DateConvert(claimperiod, this.CurrentPrivateSession.DateFormatInUse);
                    }

                    // total figure  
                    this.ResultObj.TotalClaimedAmount = decimal.Parse(TotalClaimedAmount());
                    this.ResultObj.TotalLocalAmountAlreadyPaid = decimal.Parse(TotalLocalAmountAlreadyPaid());
                    this.ResultObj.TotalLocalActualAmountLeft = decimal.Parse(TotalClaimedAmount()) - decimal.Parse(TotalLocalAmountAlreadyPaid());
                    //Commented By Agnes[10Nov2008]
                    //this.ResultObj.TotalClaimedAmount = decimal.Parse(this.TextBox_TotalAmount.Text);
                    //this.ResultObj.TotalLocalAmountAlreadyPaid = decimal.Parse(this.TextBox_TotalAmountAlreadyPaid.Text);
                    //this.ResultObj.TotalLocalActualAmountLeft = decimal.Parse(this.TextBox_Owning.Text);
                    this.ResultObj.ChequeNo = this.TextBox_ChequeNo.Text;
                    this.ResultObj.ChequeIssuesBank = this.TextBox_IssuedBank.Text;

                    #region Only execute if the status is Submitted

                    if (CurrentStatus == GonzalesClaimHeader.TypeOfClaimStatus.Submitted)
                    {
                        // get the submission date
                        this.ResultObj.SubmittedOn = DateTime.Now;

                        // get the next approver
                        if (this.CurrentPrivateSession.CurrentLoggedOnUser.NoApprover)
                        {
                            // no need approver 
                            // check for authorizer
                            #region Authorizer Check

                            if (this.CurrentPrivateSession.CurrentLoggedOnUser.NoAuthorizer)
                            {
                                // no authorizer, go straight to finance admin
                                this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.PendingForFinanceVerification;
                            }
                            else
                            {
                                bool AuthorizedNeeded = false; // default, assume no need to
                                Authoriser NextAuthorizer = this.GetAuthorizer(ref AuthorizedNeeded);

                                if (AuthorizedNeeded)
                                {
                                    // authorization required
                                    this.ResultObj.NextAuthorizer = NextAuthorizer;
                                    this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.PendingForAuthorize;
                                }
                                else
                                {
                                    // no authorizer required, so is auto
                                    // now, it is ready for finance verification
                                    this.ResultObj.Status = GonzalesClaimHeader.TypeOfClaimStatus.PendingForFinanceVerification;
                                }
                            }

                            #endregion

                        }
                        else if (this.CurrentPrivateSession.CurrentLoggedOnUser.AppRoute == ApprovingRoute.Normal)
                        {
                            this.ResultObj.NextApprover = this.CurrentPrivateSession.CurrentLoggedOnUser.PersonnelReportTo;
                        }
                        else if (this.CurrentPrivateSession.CurrentLoggedOnUser.AppRoute == ApprovingRoute.MultiLevel)
                        {
                            this.ResultObj.NextApprover = this.CurrentPrivateSession.CurrentLoggedOnUser.PersonnelReportTo;
                        }
                        else if (this.CurrentPrivateSession.CurrentLoggedOnUser.AppRoute == ApprovingRoute.Exception)
                        {
                            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
                            {
                                bool IsTheEnd = false;

                                SystemUser NextExceptionApprover = CurUserManager.GetNextApproverForExceptionCase(
                                    this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID, "", ref IsTheEnd);

                                if (!IsTheEnd && NextExceptionApprover != null)
                                {
                                    this.ResultObj.NextApprover = NextExceptionApprover;
                                }
                                else
                                {
                                    string LogID = SwissArmy.UniqueID();
                                    this.CurLogManager.LogError(LogID, "[GonzalesMyDraftDetail.SaveData] : Failed at CurUserManager.GetNextApproverForExceptionCase : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                                    this.ShowErrorMessage("Error! " + LogID);
                                }
                            }
                        }
                    }

                    #endregion

                    // collect data for detail
                    smooth = this.DetailDataCollection();

                    #region before update, create claim id if this is a not a draft

                    if (this.ResultObj.Status != GonzalesClaimHeader.TypeOfClaimStatus.Draft)
                    {
                        this.ResultObj.ClaimID = CurClaimManager.CreateNewClaimID(this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.Entity.InternalID);

                        if (this.ResultObj.ClaimID.Length == 0)
                        {
                            smooth = false;
                            string LogID = SwissArmy.UniqueID();
                            this.CurLogManager.LogError(LogID, "", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                            this.ShowErrorMessage("Error! " + LogID);
                        }
                    }

                    #endregion

                    if (smooth)
                    {   // only continue to save if smooth
                        if (!CurClaimManager.UpdateClaimByClaimant(this.ResultObj))
                        {
                            smooth = false;
                            string LogID = SwissArmy.UniqueID();
                            this.CurLogManager.LogError("[GonzalesMyDraftDetail.SaveData] : Failed on CurClaimManager.UpdateClaimByClaimant :  " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
                            this.ShowErrorMessage("Error! " + LogID);
                        }

                        // Clear credit card item, if there is any
                        using (CreditCardManager CurCreditCardManager = new CreditCardManager(this.CurrentPrivateSession))
                        {
                            if (!CurCreditCardManager.ClearCreditCardItems(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID))
                            {
                                smooth = false;
                                string LogID = SwissArmy.UniqueID();
                                this.CurLogManager.LogError("[GonzalesMyDraftDetail.SaveData] : Failed on CurCreditCardManager.ClearCreditCardItems : " + CurCreditCardManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
                                this.ShowErrorMessage("Error! " + LogID);
                            }
                        }
                    }

                }
            }
            else
            {
                smooth = false;
                string LogID = SwissArmy.UniqueID();
                this.CurLogManager.LogError("[GonzalesMyDraftDetail.SaveData] : Failed on CurClaimManager.GetClaimByInternalID('" + this.ClaimInternalID + "') : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
                this.ShowErrorMessage("Error! " + LogID);
            }

        }

        return smooth;
    }
    #endregion

    #region DetailDataCollection
    protected bool DetailDataCollection()
    {
        bool smooth = true;
        bool IsFirstRow = true;        
        int CellCounter = 1;

        foreach (TableRow DetailRow in this.Table_ClaimDetailGrid.Rows)
        {
            CellCounter = 2;

            if (!IsFirstRow)
            {
                GonzalesClaimItem CurClaimItem = new GonzalesClaimItem(DetailRow.ID);
                //CurClaimItem.Order = Order++;

                #region Record the original order
                for (int x = 0; x < this.ClaimDetailIDList.Count; x++)
                {
                    if (this.ClaimDetailIDList[x].ToString().CompareTo(DetailRow.ID) == 0)
                    {
                        CurClaimItem.Order = x;
                        break;
                    }
                }
                #endregion

                #region 1. Expense Type / Claim Type

                DropDownList DropDownClaimType = (DropDownList)DetailRow.Cells[CellCounter].Controls[0];                
                if (DropDownClaimType.SelectedIndex > 0)
                {
                    CurClaimItem.ClaimType = new ClaimType(DropDownClaimType.SelectedValue, DropDownClaimType.SelectedItem.Text);
                }

                #endregion 

                #region 2. Detail type 
                
                CellCounter++;
                HiddenField HiddenField_DetailType = (HiddenField)DetailRow.Cells[CellCounter].Controls[0];
                CurClaimItem.ClaimDetailType = ClaimManager.GetClaimDetailTypeFromCode(Convert.ToInt32(HiddenField_DetailType.Value));
                
                #endregion

                #region 3. Is Personal

                CellCounter++;
                HiddenField HiddenField_IsPersonal = (HiddenField)DetailRow.Cells[CellCounter].Controls[0];
                //CurClaimItem.IsPersonnal = (Convert.ToInt32(HiddenField_IsPersonal.Value) == 1);
                
                #endregion

                #region 4. Country

                CellCounter ++;                
                DropDownList DropDownCountry = (DropDownList)DetailRow.Cells[CellCounter].Controls[0];
                if (DropDownCountry.SelectedIndex > 0)
                {
                    CurClaimItem.Country = new Country(DropDownCountry.SelectedValue, DropDownCountry.SelectedItem.Text);
                }

                #endregion

                #region 5. City

                CellCounter++;
                TextBox TextBox_City = (TextBox)DetailRow.Cells[CellCounter].Controls[0];
                CurClaimItem.City = TextBox_City.Text;

                #endregion

                #region 6. Date

                CellCounter++;
                TextBox TextBox_ClaimDate = (TextBox)DetailRow.Cells[CellCounter].Controls[0];
                try
                {
                    CurClaimItem.ClaimDate = (TextBox_ClaimDate.Text.Length > 0) ? SwissArmy.DateConvert(TextBox_ClaimDate.Text, this.CurrentPrivateSession.DateFormatInUse) : DateTime.MinValue;

                    if (TextBox_ClaimDate.Text.Length > 0 && CurClaimItem.ClaimDate == DateTime.MinValue)
                    {
                        smooth = false;
                        this.ShowErrorMessage("Invalid Claim Date Format");
                    }
                    //added by agnes [09 Oct 2009]
                    if (CurClaimItem.ClaimDate.Year < 2006 && CurClaimItem.ClaimDate > DateTime.MinValue)
                    {
                        smooth = false;
                        this.ShowErrorMessage(this.InvalidDateFormat);
                    }
                    
                }
                catch (Exception)
                {
                    this.ShowErrorMessage(this.InvalidDateFormat);
                    smooth = false;
                }
                CellCounter++;

                #endregion

                #region 7. Description

                CellCounter++;
                TextBox TextBox_Description = (TextBox)DetailRow.Cells[CellCounter].Controls[0];
                CurClaimItem.Description = TextBox_Description.Text;

                #endregion

                #region 8. Remarks

                CellCounter++;
                TextBox TextBox_Remarks = (TextBox)DetailRow.Cells[CellCounter].Controls[0];
                CurClaimItem.Remarks = TextBox_Remarks.Text;

                #endregion

                #region 9. Amount Claimed

                CellCounter++;
                TextBox TextBox_AmountClaimed = (TextBox)DetailRow.Cells[CellCounter].Controls[0];
                try
                {
                    if (TextBox_AmountClaimed.Text.Trim().Length > 0)
                    {
                        CurClaimItem.ClaimedAmount = Convert.ToDecimal(TextBox_AmountClaimed.Text);
                    }
                }
                catch (Exception ex)
                {
                    this.ShowErrorMessage("Invalid Claim Amount");
                    smooth = false;
                }

                #endregion 

                #region 10. GST

                CellCounter++;
                TextBox TextBox_GASTTAX = (TextBox)DetailRow.Cells[CellCounter].Controls[0];
                if (TextBox_GASTTAX.Text.Trim().Length > 0)
                {
                    CurClaimItem.Tax = Convert.ToDecimal(TextBox_GASTTAX.Text);
                }

                #endregion

                #region 11. Claimed Currency

                CellCounter++;
                if (CurClaimItem.ClaimDetailType == TypeOfClaimDetail.Cash)
                {
                    DropDownList DropDownCurrency = (DropDownList)DetailRow.Cells[CellCounter].Controls[0];
                    if (DropDownCurrency.SelectedIndex >= 0)
                    {
                        CurClaimItem.ExchangeCurrency = CurClaimItem.ClaimedAmountCurrency = new Currency(DropDownCurrency.SelectedValue, DropDownCurrency.SelectedItem.Text);
                    }
                }
                else if (CurClaimItem.ClaimDetailType == TypeOfClaimDetail.CreditCard)
                {
                    TextBox TextBox_Currency = (TextBox)DetailRow.Cells[CellCounter].Controls[1];
                    CurClaimItem.ExchangeCurrency = CurClaimItem.ClaimedAmountCurrency = new Currency(TextBox_Currency.Text, TextBox_Currency.Text);                     
                }
            

                #endregion

                #region 12. ExRate

                CellCounter++;
                TextBox TextBox_ExRateFigure = (TextBox)DetailRow.Cells[CellCounter].Controls[0];
                if (TextBox_ExRateFigure.Text.Trim().Length > 0)
                {
                    CurClaimItem.ExchangeRate = float.Parse(TextBox_ExRateFigure.Text);
                }

                #endregion

                #region 13. Local amount / Amount Out

                CellCounter++;
                TextBox TextBox_LocalAmount = (TextBox)DetailRow.Cells[CellCounter].Controls[0];                
                if (TextBox_LocalAmount.Text.Trim().Length > 0)
                {
                    CurClaimItem.AmountOut = Convert.ToDecimal(TextBox_LocalAmount.Text);
                    CurClaimItem.AmountOutCurrency = this.CurrentPrivateSession.CurrentLoggedOnUser.DefaultCurrency;
                }

                #endregion

                #region 14. Having Receipts

                CellCounter++;
                CheckBox CheckBox_HavingReceipt = (CheckBox)DetailRow.Cells[CellCounter].Controls[0];
                CurClaimItem.HavingReceipts = CheckBox_HavingReceipt.Checked;

                #endregion

                #region 15. Project ID

                CellCounter++;
                TextBox TextBox_ProjectID = (TextBox)DetailRow.Cells[CellCounter].Controls[0];
                CurClaimItem.ProjectID = TextBox_ProjectID.Text;

                #endregion

                #region 16. Expand

                CellCounter++;
                HiddenField HiddenField_Parent = (HiddenField)DetailRow.Cells[CellCounter].Controls[0];
                CurClaimItem.ParentID = HiddenField_Parent.Value;

                #endregion

                // added into the collection, check for validation
                if (DropDownClaimType.SelectedIndex > 0 || TextBox_City.Text.Length > 0 || TextBox_ClaimDate.Text.Length > 0 ||
                    TextBox_Description.Text.Length > 0 || TextBox_Remarks.Text.Length > 0 || decimal.Parse(TextBox_AmountClaimed.Text) > 0 ||
                    CheckBox_HavingReceipt.Checked || TextBox_ProjectID.Text.Length > 0) 
                {
                    // any on above is filled, will consider as non-blank
                    this.ResultObj.ClaimDetails.Add(CurClaimItem);
                }
            }

            IsFirstRow = false; 
        }

        return smooth;
    }

    #endregion    

    #region CalculateTotalForDisplay
    public void CalculateTotalForDisplay()
    {
        // calculation total is only for the first time
        // it will store in the viewstate later        
        Entity CurEntity = null;
        GonzalesCompany CurCompany = null;

        using (EntityManager CurEntityManager = new EntityManager(this.CurrentPrivateSession))
        {
            CurEntity = CurEntityManager.GetEntityDetailByCode(this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.Entity.InternalID);            
        }

        using (CompanyManager CurCompanyManager = new CompanyManager(this.CurrentPrivateSession))
        {
            CurCompany =  CurCompanyManager.GetCompanyByID(this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.InternalID);
        }
        //this.CreditCardPaymentType = CurEntity.CreditCardPaymentType;
        this.CreditCardPaymentType = CurCompany.CreditCardPaymentType;

        // start calculate
        decimal TotalClaimed = 0, TotalOwn = 0, TotalPaid = 0;

        // Less Advance is, Total Claimed - Total Own From Company
        // That will be the actual amount company need to pay the claimant

        for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
        {
            bool IsPersonal = (((HiddenField)this.Table_ClaimDetailGrid.Rows[x].Cells[3].Controls[0]).Value.CompareTo("1") == 0);

            decimal LocalAmount = Convert.ToDecimal(((TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[15].Controls[0]).Text);
            TypeOfClaimDetail DetailType = ClaimManager.GetClaimDetailTypeFromCode(Convert.ToInt32(((HiddenField)this.Table_ClaimDetailGrid.Rows[x].Cells[3].Controls[0]).Value));

            // for watever been display
            if (!IsPersonal)
            {
                TotalClaimed += LocalAmount;
            }

            if (DetailType == TypeOfClaimDetail.CreditCard)
            {
                TotalPaid += LocalAmount;
            }
        }

        // owning is to own company any personal expense
        // take for example, personnel claimed 1000, which 200 is personal expense
        // company already paid the 1000, and TotalClaimed is all the amount wihout the personal claim
        TotalOwn = TotalClaimed - TotalPaid;

        this.TextBox_TotalAmount.Text = TotalClaimed.ToString();
        this.TextBox_Owning.Text = TotalOwn.ToString();

        if (!this.ClaimHavingCreditCard)
        {
            this.TextBox_Owning.CssClass = "GridViewItemHighLightRed";
            this.TextBox_Owning.Text = TotalClaimed.ToString();

            this.TextBox_TotalAmountAlreadyPaid.Text = "0";
            this.TextBox_TotalAmountAlreadyPaid.Attributes["onclick"] = "NoEdit(this);";
            this.TextBox_TotalAmountAlreadyPaid.TabIndex = -1;
            this.TextBox_TotalAmountAlreadyPaid.CssClass = "DetailGridTextBoxNoEdit";
        }
        else if (this.CreditCardPaymentType == TypeOfCreditCardPayment.PaidByCompany && this.ClaimHavingCreditCard)
        {
            this.TextBox_Owning.CssClass = "GridViewItemHighLightRed";
            this.TextBox_Owning.Text = TotalOwn.ToString();

            this.TextBox_TotalAmountAlreadyPaid.Text = TotalPaid.ToString();
            this.TextBox_TotalAmountAlreadyPaid.Attributes["onclick"] = "NoEdit(this);";
            this.TextBox_TotalAmountAlreadyPaid.TabIndex = -1;
            this.TextBox_TotalAmountAlreadyPaid.CssClass = "DetailGridTextBoxNoEdit";
        }
        else if (this.CreditCardPaymentType == TypeOfCreditCardPayment.PaidByEmployee && this.ClaimHavingCreditCard)
        {
            // paid by employee will not havce any owning

            this.TextBox_Owning.CssClass = "GridViewItemHighLightRed";
            this.TextBox_Owning.Text = TotalClaimed.ToString();

            this.TextBox_TotalAmountAlreadyPaid.Text = "0";
            this.TextBox_TotalAmountAlreadyPaid.Attributes["onclick"] = "DefaultValue(this, true);";
            this.TextBox_TotalAmountAlreadyPaid.CssClass = "DetailGridTextBox";
        }
        

    }
    #endregion

    #region AmountLimitValidation
    
    // This function is to check the claim type if agains any policy
    // only those exceptional claim type will be shown
    // if exceed policy, show warning button, it it is strict claim type policy, don't allow for submission

    protected bool AmountLimitValidation()
    {
        bool smooth = true;
        bool PolicyPass = true; // reset first        

        using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
        {
            ClaimTypeLimitPolicies PolicyCollections = null;
            if ((PolicyCollections = CurClaimManager.GetClaimItemLimitPolicies(this.CurrentPrivateSession.CurrentLoggedOnUser, this.ClaimInternalID)) != null)
            {
                // now, start to show warning if needed.
                for (int x = 0; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
                {
                    for (int y = 0; y < PolicyCollections.Count; y++)
                    {
                        // fount it!, need to validate
                        if (PolicyCollections[y].ClaimDetalID.CompareTo(this.Table_ClaimDetailGrid.Rows[x].ID) == 0)
                        {
                            // check if this is a entertainment claim
                            TextBox TextBox_Remarks = (TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[9].Controls[0];
                            if (TextBox_Remarks.Text.IndexOf("[ENT]") >= 0)
                            {
                                #region Is Entertainment

                                int TotalParticipants = Int32.Parse(TextBox_Remarks.Text.Substring(TextBox_Remarks.Text.LastIndexOf(",") + 1));
                                decimal TotalAmount = decimal.Parse(((TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[15].Controls[0]).Text);
                                decimal AmountPerHead = Math.Round(TotalAmount / TotalParticipants, 2);

                                if ((AmountPerHead * PolicyCollections[y].ExRateFigure) > PolicyCollections[y].LimitAmount)
                                {
                                    // display warning
                                    StringBuilder MessageBuilder = new StringBuilder();
                                    MessageBuilder.AppendLine(this.LimitExceed + "\n");
                                    MessageBuilder.AppendLine(this.LimitPerHead + ": " + AmountPerHead);
                                    MessageBuilder.AppendLine(this.LimitAmount + ": " + PolicyCollections[y].LimitCurrency.DisplayName + " " + PolicyCollections[y].LimitAmount);
                                    MessageBuilder.AppendLine(this.LimitStrict + ": " + (PolicyCollections[y].Strict ? "Yes" : "No"));

                                    Image ImageWarning = new Image();
                                    ImageWarning.ImageUrl = (PolicyCollections[y].Strict) ? GonzalesImages.Icon_Warning2 : GonzalesImages.Icon_Warning;
                                    ImageWarning.ToolTip = MessageBuilder.ToString();
                                    ImageWarning.Attributes["onclick"] = "alert(this.title);";

                                    PolicyPass = (PolicyCollections[y].Strict) ? false : PolicyPass;

                                    this.Table_ClaimDetailGrid.Rows[x].Cells[18].Controls.Add(ImageWarning);

                                    smooth = false;
                                    break;
                                }

                                #endregion
                            }
                            else
                            {
                                #region Non Entertainment

                                if (Math.Round((PolicyCollections[y].TotalClaimedInPeriod * PolicyCollections[y].ExRateFigure),2) > PolicyCollections[y].LimitAmount)
                                {
                                    // display warning
                                    StringBuilder MessageBuilder = new StringBuilder();
                                    MessageBuilder.AppendLine("Exceed Limit\n");
                                    MessageBuilder.AppendLine("Amount claimed to-date: " + PolicyCollections[y].TotalClaimedInPeriod);
                                    MessageBuilder.AppendLine("Limit Amount: " + PolicyCollections[y].LimitCurrency.DisplayName + " " + PolicyCollections[y].LimitAmount);
                                    MessageBuilder.AppendLine("Strict: " + (PolicyCollections[y].Strict ? "Yes" : "No"));

                                    Image ImageWarning = new Image();
                                    ImageWarning.ImageUrl = (PolicyCollections[y].Strict) ? GonzalesImages.Icon_Warning2 : GonzalesImages.Icon_Warning;
                                    ImageWarning.ToolTip = MessageBuilder.ToString();
                                    ImageWarning.Attributes["onclick"] = "alert(this.title);";

                                    PolicyPass = (PolicyCollections[y].Strict) ? false : PolicyPass;

                                    this.Table_ClaimDetailGrid.Rows[x].Cells[18].Controls.Add(ImageWarning);

                                    smooth = false;
                                    break;
                                }

                                #endregion
                            }
                        }
                    }   // y
                }   // x

                // display message if needed
                if (!smooth)
                {                                        
                    for (int x = 0; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
                    {
                        this.Table_ClaimDetailGrid.Rows[x].Cells[18].Visible = true;
                    }

                    // built table, to show
                    if (PolicyPass) // policy pass indicate strict or non-strict policy
                    {
                        this.Table_PolicyChecking_Pass.Rows[0].Cells[0].Text = "There are restrictions to this claim. Please proceed if you are ok";
                        this.Table_PolicyChecking_Pass.Visible = true;
                    }
                    else
                    {
                        this.Table_PolicyChecking_Fail.Rows[0].Cells[0].Text = "This claim exceeds the approved limit. Please modify the claim or consult finance.";
                        this.Table_PolicyChecking_Fail.Visible = true;
                    }                    
                }
            }
            else
            {
                string LogID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.PolicyEnvironmentSetup] : Failed at CurClaimManager.GetClaimItemLimitPolicies() : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage("Error! " + LogID);
            }
        }

        return smooth;
    }

    #endregion

    #region ClaimDateValidation

    protected bool ClaimDateValidation()
    {
        bool smooth = true;
        SystemUser Claimant = null;

        //get the user comapny first
        UserManager CurUserManager = new UserManager(this.CurrentPrivateSession);
        Claimant = CurUserManager.GetUserByInternalID(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);

        if (Claimant != null)
        {
            CompanyManager CurCompanyManager = new CompanyManager(this.CurrentPrivateSession);
            GonzalesCompany CurCompany = CurCompanyManager.GetCompanyByID(Claimant.FromCompany.InternalID);

            int ExpiryDays = Convert.ToInt32(CurCompany.ExpiryDate);
            TimeSpan t = new TimeSpan(ExpiryDays, 0, 0, 0);

            if (ExpiryDays > 0)
            {
                DateTime ExpiryDate = DateTime.Today.Subtract(t); //DateTime.Now.Subtract(t);
                for (int x = 1; x < this.Table_ClaimDetailGrid.Rows.Count; x++)
                {
                    TextBox TextBoxClaimDate = (TextBox)this.Table_ClaimDetailGrid.Rows[x].Cells[7].Controls[0];
                    if(TextBoxClaimDate.Text != "")
                    {
                        if (SwissArmy.DateConvert(TextBoxClaimDate.Text, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedDateFormat) < ExpiryDate)
                        {
                            ShowErrorMessage(this.ExpiryMessage1 + ExpiryDays + this.ExpiryMessage2);
                            smooth = false;
                            break;
                        }
                    }
                }
            }
        }
        else
            smooth = true;

        return smooth;
    }

    #endregion

    #region GetAuthorizer

    protected Authoriser GetAuthorizer(ref bool AuthorizedNeeded)
    {
        SystemUsers AuthorizersCollection = null;
        SystemUser Claimant = null;
        Authoriser ResultAuthorizer = null;

        #region 1. Get list of Authorizers

        using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
        {
            Claimant = CurUserManager.GetUserByInternalID(this.ResultObj.ClaimedBy.InternalID);

            if (Claimant != null)
            {
                AuthorizersCollection = CurUserManager.GetAuthorizersByEntity(Claimant.FromCompany.Entity.InternalID);

                if (AuthorizersCollection == null)
                {
                    string LogID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.GetAuthorizer] : Failed at CurUserManager.GetAuthorizersByEntity('" + Claimant.FromCompany.Entity.InternalID + "') : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    this.ShowErrorMessage("Error! " + LogID);
                }
            }
            else
            {
                string LogID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(LogID, "[GonzalesClaimsPendingForApprovalDetail.GetAuthorizer] : Failed at CurUserManager.GetUserByInternalID('" + this.ResultObj.ClaimedBy.InternalID + "') : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage("Error! " + LogID);
            }
        }

        #endregion

        #region 2. Get simple summary of claim detail with weekly limit (Not using)

        /*
        if (AuthorizersCollection != null)
        {
            MasterBaseCollection CurrencyCollection = null;

            // diff currency, need to convert
            using (CurrencyManager CurCurrencyManager = new CurrencyManager(this.CurrentPrivateSession))
            {
                CurrencyCollection = CurCurrencyManager.GetLatestExchangeRate(this.ResultObj.LocalCurrency);
            }

            using (ClaimManager CurClaimManager = new ClaimManager(this.CurrentPrivateSession))
            {
                ClaimItems CurClaimItems = CurClaimManager.GetSimpleClaimItemsByClaimHeaderWithWeeklyLmit(this.ClaimInternalID, Claimant.InternalID);

                if (CurClaimItems != null)
                {
                    // CurrentMaxAmount is to record down the current maximum amount spent in a particular week
                    // CurrentMaxAmount will include current claim amount even if this is in draft
                    decimal CurrentMaxAmount = 0;

                    // get the max amount first
                    for (int x = 0; x < CurClaimItems.Count; x++)
                    {
                        GonzalesClaimItemWithWeeklyLimit CurrentItem = (GonzalesClaimItemWithWeeklyLimit)CurClaimItems[x];
                        CurrentMaxAmount = ((CurrentItem.TotalSpentInWeek + CurrentItem.AmountOut) > CurrentMaxAmount) ? (CurrentItem.TotalSpentInWeek + CurrentItem.AmountOut) : CurrentMaxAmount;                        
                    }

                    for (int x = 0; x < AuthorizersCollection.Count; x++)
                    {
                        Authoriser CurrentAuthorizer = (Authoriser)AuthorizersCollection[x];

                        decimal MinLimitInLocal = 0, MaxLimitInLocal = 0;
                        
                        // convert to local currency
                        if (this.ResultObj.LocalCurrency.InternalID.CompareTo(CurrentAuthorizer.LimitCurrency.InternalID) == 0)
                        {
                            // same to local currency 
                            MinLimitInLocal = CurrentAuthorizer.MinLimit;
                            MaxLimitInLocal = CurrentAuthorizer.MaxLimit;
                        }
                        else
                        {
                            // compare with foreign currency
                            for (int y = 0; y < CurrencyCollection.Count; y++)
                            {
                                Currency CurCurrency = (Currency)CurrencyCollection[y];

                                if (CurCurrency.InternalID.CompareTo(CurrentAuthorizer.LimitCurrency.InternalID) == 0)
                                {
                                    MinLimitInLocal = CurrentAuthorizer.MinLimit * decimal.Parse(CurCurrency.ExchangeRate.ToString());
                                    MaxLimitInLocal = CurrentAuthorizer.MaxLimit * decimal.Parse(CurCurrency.ExchangeRate.ToString());
                                    break;
                                }
                            }
                        }

                        // ready to compare now
                        if (CurrentMaxAmount >= MinLimitInLocal &&
                            CurrentMaxAmount <= MaxLimitInLocal)
                        {
                            // found the authorizer
                            AuthorizedNeeded = true;
                            ResultAuthorizer = CurrentAuthorizer;
                            break;
                        }
                    }
                }
                else
                {
                    string LogID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(LogID, "[GonzalesMyDraftDetail.GetAuthorizer] : Failed at CurClaimManager.GetSimpleClaimItemsByClaimHeaderWithWeeklyLmit('" + this.ClaimInternalID + "', '" + Claimant.InternalID + "') : " + CurClaimManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    this.ShowErrorMessage("Error! " + LogID);
                }
            }
        }

        */
        #endregion

        #region 2. Check if total claim exceed the limit.
        
        if (AuthorizersCollection != null)
        {
            MasterBaseCollection CurrencyCollection = null;

            // diff currency, need to convert
            using (CurrencyManager CurCurrencyManager = new CurrencyManager(this.CurrentPrivateSession))
            {
                CurrencyCollection = CurCurrencyManager.GetLatestExchangeRate(this.ResultObj.LocalCurrency);
            }

            for (int x = 0; x < AuthorizersCollection.Count; x++)
            {
                Authoriser CurrentAuthorizer = (Authoriser)AuthorizersCollection[x];

                decimal MinLimitInLocal = 0, MaxLimitInLocal = 0;

                // convert to local currency
                if (this.ResultObj.LocalCurrency.InternalID.CompareTo(CurrentAuthorizer.LimitCurrency.InternalID) == 0)
                {
                    // same to local currency 
                    MinLimitInLocal = CurrentAuthorizer.MinLimit;
                    MaxLimitInLocal = CurrentAuthorizer.MaxLimit;
                }
                else
                {
                    // compare with foreign currency
                    for (int y = 0; y < CurrencyCollection.Count; y++)
                    {
                        Currency CurCurrency = (Currency)CurrencyCollection[y];

                        if (CurCurrency.InternalID.CompareTo(CurrentAuthorizer.LimitCurrency.InternalID) == 0)
                        {
                            MinLimitInLocal = CurrentAuthorizer.MinLimit * decimal.Parse(CurCurrency.ExchangeRate.ToString());
                            MaxLimitInLocal = CurrentAuthorizer.MaxLimit * decimal.Parse(CurCurrency.ExchangeRate.ToString());
                            break;
                        }
                    }
                }

                // ready to compare now
                if (this.ResultObj.TotalClaimedAmount >= MinLimitInLocal && this.ResultObj.TotalClaimedAmount <= MaxLimitInLocal)
                {
                    // found the authorizer
                    AuthorizedNeeded = true;
                    ResultAuthorizer = CurrentAuthorizer;
                    break;
                }
            } 
        }
        
        #endregion

        return ResultAuthorizer;


    }

    #endregion

    #region TotalClaimedAmount
    protected string TotalClaimedAmount()
    {
        bool IsFirstRow = true;
        decimal LocalAmt = 0;

        foreach (TableRow DetailRow in this.Table_ClaimDetailGrid.Rows)
        {
            if (!IsFirstRow)
            {
                #region 3. Is Personal

                HiddenField HiddenField_IsPersonal = (HiddenField)DetailRow.Cells[4].Controls[0];

                #endregion
             
                #region 13. Local amount / Amount Out
                TextBox TextBox_LocalAmount = (TextBox)DetailRow.Cells[15].Controls[0];
                if (TextBox_LocalAmount.Text.Trim().Length > 0)
                {
                    if(HiddenField_IsPersonal.Value == "0")
                        LocalAmt += Convert.ToDecimal(TextBox_LocalAmount.Text);
                }

                #endregion
            }
            IsFirstRow = false; 
        }

        return LocalAmt.ToString();
    }
    #endregion

    #region TotalLocalAmountAlreadyPaid
    protected string TotalLocalAmountAlreadyPaid()
    {
        bool IsFirstRow = true;
        decimal LocalAmt = 0;

        foreach (TableRow DetailRow in this.Table_ClaimDetailGrid.Rows)
        {
            if (!IsFirstRow)
            {
                #region 2. Detail Type

                HiddenField HiddenField_DetailType = (HiddenField)DetailRow.Cells[3].Controls[0];

                #endregion

                #region 13. Local amount / Amount Out
                TextBox TextBox_LocalAmount = (TextBox)DetailRow.Cells[15].Controls[0];
                if (TextBox_LocalAmount.Text.Trim().Length > 0)
                {
                    if (HiddenField_DetailType.Value == "1" && this.CreditCardPaymentType == TypeOfCreditCardPayment.PaidByCompany)
                        LocalAmt += Convert.ToDecimal(TextBox_LocalAmount.Text);
                }

                #endregion
            }
            IsFirstRow = false;
        }

        return LocalAmt.ToString();
    }
    #endregion

    #endregion

    #region Javascripts

    #region GeneralVariable
    public void GeneralVariable()
    {        
        StringBuilder JSBuilder = new StringBuilder();
        JSBuilder.AppendLine("<script language='javascript'>");
        JSBuilder.AppendLine("var TypeCreditCardPayment = " + CreditCardManager.GetCreditCardPaymentTypeInCode(this.CreditCardPaymentType) + ";");
        JSBuilder.AppendLine("var UsingCreditCard = " + ((this.ClaimHavingCreditCard)?1:0) + ";");
        JSBuilder.AppendLine("var ValidationText = '" + this.ValidationText + "';");
        JSBuilder.AppendLine("var CurrentDateFormat = '" + SwissArmy.DateFormatForDisplay(this.CurrentPrivateSession.DateFormatInUse, "/") + "';"); 

        JSBuilder.AppendLine("</script>");

        // done, generate on the page
        if (!this.ClientScript.IsClientScriptBlockRegistered("GeneralVariable"))
        {
            this.ClientScript.RegisterClientScriptBlock(Type.GetType("System.String"), "GeneralVariable", JSBuilder.ToString());
        }
    }
    #endregion

    #region GenerateExchangeRate
    public void GenerateExchangeRate()
    {
        MasterBaseCollection ExchangeRateFigures = null;
        StringBuilder JSBuilder = new StringBuilder();
        JSBuilder.AppendLine("<script language='javascript'>");
        
        using (CurrencyManager CurCurrencyManager = new CurrencyManager(this.CurrentPrivateSession))
        {
            ExchangeRateFigures = CurCurrencyManager.GetLatestExchangeRate(this.CurrentPrivateSession.CurrentLoggedOnUser.DefaultCurrency);
            if (ExchangeRateFigures != null)
            {
                JSBuilder.AppendLine("var LocalCurrency = '" + this.CurrentPrivateSession.CurrentLoggedOnUser.DefaultCurrency.InternalID + "';");
                JSBuilder.AppendLine("var TargetCurrency = new Array(" + ExchangeRateFigures.Count + ");");
                JSBuilder.AppendLine("var ExchangeRate = new Array(" + ExchangeRateFigures.Count + ");");

                ExchangeRateFigures.Sort();
                for (int x = 0; x < ExchangeRateFigures.Count; x++)
                {
                    Currency CurCurrency = (Currency)ExchangeRateFigures[x];

                    JSBuilder.AppendLine("TargetCurrency[" + x + "] = '" + CurCurrency.InternalID + "';");
                    JSBuilder.AppendLine("ExchangeRate[" + x + "] = " + Convert.ToDecimal(CurCurrency.ExchangeRate) + ";");
                }

            }
            else
            {
                this.CurLogManager.LogError("[GonzalesMyDraftDetail.GenerateExchangeRate] : " + CurCurrencyManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
            }
        }

        JSBuilder.AppendLine("</script>");

        // done, generate on the page
        if (!this.ClientScript.IsClientScriptBlockRegistered("GenerateExchangeRate"))
        {
            this.ClientScript.RegisterClientScriptBlock(Type.GetType("System.String"), "GenerateExchangeRate", JSBuilder.ToString());
        }
    }
    #endregion

    #region GenerateCountryCurrencyRefference

    public void GenerateCountryCurrencyRefference()
    {        
        StringBuilder JSBuilder = new StringBuilder();
        JSBuilder.AppendLine("<script language='javascript'>");

        if (this.Countries != null)
        {            
            JSBuilder.AppendLine("var CountryArray = new Array(" + this.Countries.Count + ");");
            JSBuilder.AppendLine("var CurrencyArray = new Array(" + this.Countries.Count + ");");
            JSBuilder.AppendLine("var NoReceipt = '" + this.NoReceipt + "';");

            for (int x = 0; x < this.Countries.Count; x++)
            {
                Country CurCountry = (Country)this.Countries[x];

                JSBuilder.AppendLine("CountryArray[" + x + "] = '" + CurCountry.InternalID + "';");
                JSBuilder.AppendLine("CurrencyArray[" + x + "] = '" + CurCountry.CountryCurrency.InternalID + "';");
            }
        }

        JSBuilder.AppendLine("</script>");

        // done, generate on the page
        if (!this.ClientScript.IsClientScriptBlockRegistered("GenerateCountryCurrencyRefference"))
        {
            this.ClientScript.RegisterClientScriptBlock(Type.GetType("System.String"), "GenerateCountryCurrencyRefference", JSBuilder.ToString());
        }
    }

    #endregion

    #region GenerateExpenseDetail / Claim Type

    public void GenerateExpenseDetail()
    {
        if (this.ClaimTypes != null)
        {
            StringBuilder JSBuilder = new StringBuilder();
            JSBuilder.AppendLine("<script language='javascript'>");
            JSBuilder.AppendLine("var GLCode = new Array(" + this.ClaimTypes.Count + ");");

            for (int x = 0; x < this.ClaimTypes.Count; x++)
            {
                GLClaimType CurrentGL = (GLClaimType)this.ClaimTypes[x];
                JSBuilder.AppendLine("GLCode[" + x + "] = '" + CurrentGL.GLCode + "';");                
            }

            JSBuilder.AppendLine("</script>");

            // done, generate on the page
            if (!this.ClientScript.IsClientScriptBlockRegistered("GenerateExpenseDetail"))
            {
                this.ClientScript.RegisterClientScriptBlock(Type.GetType("System.String"), "GenerateExpenseDetail", JSBuilder.ToString());
            }
        }

    }

    #endregion

    #region js_TimeVariable
    public void js_TimeVariable(int minutes, int seconds, int interval, int IsNew)
    {
        string js = "<script language=JavaScript>";
        js += "var minutes = " + minutes + ";";
        js += "var seconds = " + seconds + ";";
        js += "var interval = " + interval + ";";
        js += "var isnew = " + IsNew + ";";

        // end of scripts
        js += "<";
        js += "/";
        js += "script>";


        if (!this.IsClientScriptBlockRegistered("js_TimeVariable"))
            this.RegisterClientScriptBlock("js_TimeVariable", js);
    }
    #endregion

    #region GenerateClaimedAmountLimitation
    public void GenerateClaimedAmountLimitation()
    {
        for (int i = 1; i < this.ClaimDetailIDList.Count; i++)
        {
            if (!this.ClientScript.IsClientScriptBlockRegistered("Focus"))
            {
                ClientScript.RegisterStartupScript(typeof(Page), "Focus" + i, "<script language='JavaScript'>" + "ExpenseDetailAmountValidation(document.getElementById('" + this.ClaimDetailIDList[i - 1].ToString() + "_DropDownClaimType'), document.getElementById('" + this.ClaimDetailIDList[i - 1].ToString() + "_TextBoxAmount'));" + "</script>");
                    //"alert(document.getElementById('" + this.ClaimDetailIDList[i - 1].ToString() + "_TextBoxAmount'));" + "</script>");

            }
               // "ExpenseDetailAmountValidation(document.getElementById('" + this.ClaimDetailIDList[i-1].ToString() + "_DropDownClaimType'), document.getElementById('" + this.ClaimDetailIDList[i-1].ToString() + "_TextBoxAmount'));" + "</script>");
        }
    }
    #endregion

    #endregion

}
